Click to See Complete Forum and Search --> : some simple UDP questions


lab1
December 19th, 2008, 08:17 AM
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!!

#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);
}

Richard.J
December 19th, 2008, 09:51 AM
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

Richard.J
December 19th, 2008, 09:52 AM
One more thing: identifiers should not start with '_' because those are reserved for the OS.