开发者

Can select() be used for clients, not just servers?

开发者 https://www.devze.com 2022-12-10 03:44 出处:网络
I\'d like to make a TCP client that makes multiple connections while a select(开发者_高级运维) loop that receives data from them is running in a separate thread. I\'m not sure this is possible, though

I'd like to make a TCP client that makes multiple connections while a select(开发者_高级运维) loop that receives data from them is running in a separate thread. I'm not sure this is possible, though, because the select() loop is already running and thus I don't see how it would "notice" a new socket was added even if the thread-safety issues are dealt with.

Is there a way to do this, or must I spawn a new thread and use recv() every time I make a new connection?

(Edited for clarity.)


Of course it is possible. The select() function accepts file handles in three sets, one for read, one for write and one for errors. Just add your socket to the read set, and you'll be noticed when the server has sent you something.

This page has code showing how this is done.


Another good reason to select() on client sockets is to track outgoing TCP connections progress. This allows, for example, to setup connection timeout.

  • Set client socket to be non-blocking.
  • Call connect(). Probably it would return with EINPROGRESS error set (connection is in progress, you are not blocked because socket is non-blocking).
  • Now select() with FD_SET configured to track client-socket as 'write-ready'. Also you can set timeout.
  • Analyze select() result.
  • Analyze if last client socket operation was failed or succeed.

The most useful thing is you can use this on several sockets in different state. So you get truly non-blocking handling of number of sockets (client, server, outgoing, listening, accepted ...). And all of this with only one thread.


One simple way to do this is to also select on a pipe. After you arrange things so that the thread will also select on the new connection, you write a single byte on the pipe. This causes the thread to come out of select. When it notices the pipe is readable, it reads the bytes to 'reset' the pipe so it's ready for use again, updates its file descriptor sets, and goes back to selecting.

0

精彩评论

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