This topic is now archived and is closed to further replies.


Non blocking receiving help..

Recommended Posts

bzroom    647
I am writing a winsock class and this was the first receive code i used. return recv(dsocket, data, size, 0); Until I tried to use it in my game on the server but with out the clients sending any data. It just froze the thread. So I looked this up:
	fd_set input_set, exc_set;
	int s, nfds; 
	timeval timeout;


	nfds = 1;


	s = select(nfds,&input_set,NULL,&exc_set,&timeout);

	if (s > 0) // Is there data coming in?

		if (FD_ISSET(dsocket,&exc_set)) // There was an Error?

			return -1;

		if ((FD_ISSET(dsocket, &input_set))) // Actual Data coming through?

			return recv(dsocket, data, size, 0);

	return 0;
The problem is I seem to get random parts of packets. After I receive the data I look to see if the first byte is the update byte, but since it seems like random data i only get a first byte as an update byte half as often and the player lags way more. Also sometimes it returns like 122, and sometimes it returns 256 (this size of my buffer) and I know the messages sent are not 256. How can I get it to return 0 until the whole message has arrived?

Share this post

Link to post
Share on other sites
foofightr    130
Welcome to streaming protocols... on the sending end, send() is free to break up a big packet into many smaller ones or pack many small packets into a big one. On the receiving end, recv() is free to return many packets worth of data at once, or to stagger a big packet into many calls to recv. The point is that message boundaries (packets) are not preserved, instead they are treated as one consecutive buffer.

If you want to work with separate packets (and you do), you either have to use fixed size packets (lame) or prefix headers to your packets, that have length fields to tell you how to reconstruct packets from the buffer(s) read by recv. The latter is a bit more work but well worth it.

Share this post

Link to post
Share on other sites