Advertisement

Question about the "correct" sockets to use

Started by April 18, 2004 09:16 PM
0 comments, last by Peon 20 years, 9 months ago
As I wrote in a previous post, I would like to make a small real time game, using Windows Sockets. I did a little research and went over a few tutorials to figure out how I could go about doing this. I tried one tutorial, but have found that blocking sockets won''t work for me (my client needs to continue processing/rendering/etc... though perhaps blocking would work for the server) I did see one tutorial that used a slightly different method, using "async sockets" that made use of the windows message pump to find out if sockets needed attention. I wasn''t able to try this, as I was doing my testing in console windows, but do asyncronous(sp?) sockets of this form seem appropriate for a real time application? I got the impression that different tutorials advocated different things.
Peon
Use select() with a timeout of 0 to find out if the socket can be read, and only read it if its ready. This way it never blocks. That''s what I''m doing and it works great.

BTW, if you''re using UDP, you only ever need to have 1 socket at a time(not 1 per connection), which makes it quite efficient.

select() is quite confusing if you''ve never used it, so here is some pseudocode to help you understand how to use it.

int read_socket(int sock, void* buf, size_t len)
{

fd_set read;
FD_ZERO(&read);
FD_SET(s, &read);
timeval nowait = {0, 0}; // set timeval to 0 (return immediately)

// notice we supply sock+1 for the nfds parameter
// this is not nessesary for winsock but is nessesary
// for most other socket implementations
if(select(sock+1, &read, 0, 0, &nowait))
return recv(sock, buf, len, 0);

return 0;
}

void check_network()
{
char buffer[1024];
int retval;

// read and process all packets received
while((retval = read_socket(g_sock, buffer, sizeof(buffer))) > 0) process_packet(buffer, retval);
}

Basically, you call check_network() in your main loop along with render(), etc. No need for separate threads or anything like that. This is a simple, elegant(IMHO) solution and it works very well. On top of that, it''s totally crossplatform so porting will be a cinch.

I hope you find that information useful. I didn''t plan to write that much, but it''s good to jog the memory once in a while..

-Melekor

This topic is closed to new replies.

Advertisement