select() 可以用于客户端,而不仅仅是服务器吗?
我想创建一个建立多个连接的 TCP 客户端,同时从这些连接接收数据的 select() 循环在单独的线程中运行。不过,我不确定这是否可能,因为 select() 循环已经在运行,因此即使处理了线程安全问题,我也不知道它如何“注意到”添加了新套接字。
有没有办法做到这一点,或者我必须生成一个新线程并在每次建立新连接时使用recv()?
(为了清晰起见进行了编辑。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然有可能。
select()
函数接受三组文件句柄,一个用于读取,一个用于写入,一个用于错误。只需将您的套接字添加到读取集中,当服务器向您发送某些内容时您就会注意到。此页面包含显示如何完成此操作的代码。
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.
在客户端套接字上 select() 的另一个好理由是跟踪传出 TCP 连接进度。例如,这允许设置连接超时。
最有用的是你可以在不同状态的多个套接字上使用它。因此,您可以获得真正的非阻塞处理套接字数量(客户端、服务器、传出、侦听、接受...)。而所有这一切只需要一个线程。
Another good reason to select() on client sockets is to track outgoing TCP connections progress. This allows, for example, to setup connection timeout.
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.
一种简单的方法是在管道上也
select
。在您安排好事情以便线程也可以在新连接上选择之后,您可以在管道上写入一个字节。这会导致线程退出select
。当它注意到管道可读时,它会读取字节以“重置”管道,以便再次使用它,更新其文件描述符集,然后返回到选择。One simple way to do this is to also
select
on a pipe. After you arrange things so that the thread will alsoselect
on the new connection, you write a single byte on the pipe. This causes the thread to come out ofselect
. 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 toselect
ing.