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




Reply With Quote