问题
I have a bit of a glitch in my game just now, everything runs fine if the server is started before the client however when the client is started before the server they never connect. This is all UDP
The problem happens when the client tries to call recvfrom() before the server has started, when this happens the client never finds the server and the server never finds the client. The resulted error is a wouldblock.
If I stop the client using recvfrom and start the client before the server (the client is still sending data its just not receiving it) they both find each other no problem.
Whats the solution for this? The way its seems just now is that the client cannot call recvfrom without a server being active or it all falls apart. Is there a check that can be done to see if data is sitting on a certain port(data the server would send)? Or is there a better way to do this?
Some Code...
Server Operation - UDPSocket is a class
UDPSocket.Initialise();
UDPSocket.MakeNonBlocking();
UDPSocket.Bind(LOCALPORT);
int n = UDPSocket.Receive(&thePacket);
if (n > 0)
UDPSocket.Send(&sendPacket);
Client...
UDP.Initialise();
UDP.MakeNonBlocking();
UDP.SetDestinationAddress(SERVERIP, SERVERPORT);
serverStatus = UDP.Receive(&recvPacket);
if (serverStatus > 0)
{
//Do some things
UDP.Send(dPacket); //Try and reconnect with server
}
Thanks
回答1:
EWOULDBLOCK is not an error per se--it just means the socket was non-blocking and there was no data to read. I presume your server listens for data and replies via UDP, and the client is sending a packet when it starts and receiving the reply? If so, you may have a race condition anyway--what if the server is running but is just a bit slow, and you get EWOULDBLOCK in the client then? Will your client just exit? Perhaps you want to do a blocking receive in the client, or perhaps better yet, use select()
or WaitForMultipleEvents()
or TCP or something else.
来源:https://stackoverflow.com/questions/8106036/udp-client-started-before-server