Original Post
I'm trying to establish a connection between two computers using udp. The client sends a request packet to the server and the server sends another packet back to the client informing them. The code I am using on the client looks like this: sendAddr is the address of the server (sockaddr_in). the request is just an unsigned char. The server seems to always recieve this request even though I have made a mistake... the recvfrom function blocks so the request is only sent once. (there is no point in having the while(!registered)). When the server replies it only sends one packet which sometimes gets lost (this packet is 12 bytes). here is the server code: this process runs in a separate thread. My questions are: does the packet size play a factor in the probability that the packet will get lost? the client request (1 byte) always seems to make it to the server wheras the client reply (12 bytes) rarely makes it back to the client. (I tried wrapping the sendto function in a for(int x = 10; x--;) loop and the reply seems to make it back more often but surely this can't be the answer). does the recvfrom function have a timeout? or can you set one? rather than having to create a new thread to listen for incoming messages and have one do re-send the request every so often? and generally whats the best way to have the client send a request and then wait for a reply and then resend the request after a certain time?
char buffer[256];
// while the client is not registered with the server...
while(!registered)
{
// send the request if still not registered
sendto(this->sendSocket, (char*)&request, sizeof(request), 0, (SOCKADDR*)&this->sendAddr, sizeof(this->sendAddr));
// wait to recv a packet from the server
recvfrom(this->recvSocket, buffer, 256, 0, 0, 0);
switch(buffer[0])
{
case CLIENT_REPLY:
{
registered = true;
}
}
}
while(true)
{
char buffer[256];
sockaddr_in sender;
int length = sizeof(sender);
// recieve packet from client
recvfrom(this->recvSocket, buffer, 256, 0, (SOCKADDR*)&sender, &length);
switch(buffer[0])
{
case CLIENT_REQUEST:
{
ClientReply reply;
reply.type = CLIENT_REPLY;
sendto(this->sendSocket, (char*)&reply, sizeof(reply), 0, (SOCKADDR*)&sender, sizeof(sender));
}
}
}