|
-
December 19th, 2008, 09:17 AM
#1
some simple UDP questions
Hello,
I am writing a small UDP class, and I wanted to know 2 things:
1. how can I make it so the recvfrom() code is nonblocking?
2. can anyone convert my little class here so it works on both unix and windows?
Thanks!!
Code:
#include <UDPProgram.h>
#pragma comment(lib,"ws2_32.lib")
UDPProgram::UDPProgram(int serverPort, string serverIPAddress)
{
// Initiate use of the WinSock DLL.
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
// Create a socket and store the handle to it.
_hSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Set the protocol, port, and address information.
_serverAddr.sin_family = AF_INET;
_serverAddr.sin_port = htons(serverPort);
if(serverIPAddress=="")
{
_serverAddr.sin_addr.s_addr = INADDR_ANY;
bind(_hSocket, reinterpret_cast<sockaddr*>(&_serverAddr), sizeof(_serverAddr));
}
else
_serverAddr.sin_addr.s_addr = inet_addr(serverIPAddress.c_str());
}
UDPProgram::~UDPProgram()
{
closesocket(_hSocket);
WSACleanup();
}
void UDPProgram::Send(string msg)
{
sendto(_hSocket, message.c_str(), strlen(message.c_str())+1, 0, reinterpret_cast<sockaddr*>(&_serverAddr), sizeof(_serverAddr));
}
string UDPProgram::Receive()
{
char buf[1024] = {0};
recvfrom(_hSocket, buf, sizeof(buf), 0, 0, 0);
return string(buf);
}
-
December 19th, 2008, 10:51 AM
#2
Re: some simple UDP questions
1. you can use select() to determine if there is something available at your socket and only then call recvfrom. select() can be used with a timeout, so you can do other tasks when the call times out. But it might be a better idea to start a thread that calls recvfrom() and has some sort of callback it can call when it receives data.
2. The Windows-specific thing is the WSA... calls and closesocket instead of close.
I would put the WSA.. calls outside the class because they only need to be called once per program. If you leave them in the class, make sure they are only called once.
And you need different header files, normally the OS-specific things can be handled via #ifdef
HTH,
Richard
-
December 19th, 2008, 10:52 AM
#3
Re: some simple UDP questions
One more thing: identifiers should not start with '_' because those are reserved for the OS.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|