Advertisement

Checking for connection

Started by December 23, 2003 06:34 PM
4 comments, last by John Dowis 21 years, 1 month ago
If I have a server application with an array of sockets for clients, what is the best way to determine if a socket is being used (connected) or not? For example, I have 10 people connected, then number 3 leaves, how can I detect that 3 is disconnected so I can send the next user there, instead of slot 11? I tried using "getpeername" to see if it returns the error "WSAENOTCONN", but that doesn''t seem to work. Besids, I knowthere has to be a more direct way to test if a given socket is connected.
Implement a PING? PONG type system. Server sends PING to all its clients and if it doesn''t get PONG message in the alotted time (set by you) then it assumes the client is not responding and disconnects.
Advertisement
When a socket disconnects, recv() will return 0 for that socket. With this information, you can close that socket and move the new socket here.
Furthermore, under a non-blocking I/O model, windows should update the server upon client disconnection.

Kuphryn
Windows should do that, but you can''t depend on it. Sometimes connections time out or die from the client end and the server''s OS never notices (or takes a Loooooong time to notice)

I second Gladiator''s PING-PONG idea. It''s simple and works well.
If you use UDP (which you SHOULD be using for any networked game) then there are no "connections"; thus you can''t tell whether you''re connected or not. Of course, you only need a single socket for receiving/sending UDP packets, so you don''t even need to tell whether there will be data; just deal with the data as it comes in.

When a player hasn''t sent data for 10 seconds, drop him.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement