开发者

Disconnect idle sockets/clients C

开发者 https://www.devze.com 2023-02-28 18:11 出处:网络
I am using select() statement that handles multiple client connections using Unix C sockets. I would like to disconnect idle clients - if I don\'t get any messages from clients after a certain period.

I am using select() statement that handles multiple client connections using Unix C sockets. I would like to disconnect idle clients - if I don't get any messages from clients after a certain period. I looked at the select()'s ti开发者_如何学Cmeout functionality but that's for the whole select and not individual clients.

How would you terminate the connection for specific clients?


For a server, you typically call select in a loop. At the top of the loop, you build your file descriptor lists from the client connections. At this point, I would calculate the longest you want to wait in your select (smallest time until the next client connection should be timed out). Then call select with that timeout. After the end of the select, you check each of the connections to see if data was received, a new connection was received, or if a timeout has been reached. Process any data, open/close any connections, and then return to the top of your loop.


When you act on a connection, set a timestamp that represents the last time the socket had an event. When the idle callback for that socket finds that the difference between the current time and the timestamp is greater than the timeout, fire a timeout event and clean up the socket.

0

精彩评论

暂无评论...
验证码 换一张
取 消