TCP消息通信
您好,我想使用 tcp 连接来发送/接收消息。问题是我想发送许多消息并测量延迟。因此,我不想在每条消息发送后都收到。但是,如果我不及时处理传入的消息,程序总是会得到意想不到的结果。有什么方法可以处理recv()而不阻止我的发送消息的程序吗? 任何意见将不胜感激。
hi i want to use tcp connection to send/recv messages. The question is i want to send many messages and measure the latencies. Thus, I don't want to receive after every message sent. However, if i don't handle incoming messages in time, the program alway get unexpected result. Is there any way that I can handle recv() without blocking my program of sending msg?
Any comments would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 TCP 测量延迟可能不是最佳想法,因为 TCP 必然引入其自身的延迟(请参阅Nagle 算法)。 TCP 意味着字节流,它甚至没有明确定义的“消息”概念。
您可以将套接字设置为非阻塞,这将导致
recv( )
如果没有数据则立即返回。如果你不想通过轮询来浪费CPU,你可以使用select()< /a>
检测套接字何时有可供读取的数据。Measuring latency using TCP is maybe not the optimal idea, since TCP necessarily introduces latency of its own (see Nagle's algorithm). TCP is meant as a byte stream, it doesn't have a well-defined idea of "messages" even.
You can set the socket to be non-blocking, which will cause
recv()
to return immediately if there is no data. If you don't want to waste CPU by polling, you can instead useselect()
to detect when the socket has data available for reading.您可以使用
select()
来测试传入数据是否可用。You can use
select()
to test whether incoming data is available.我在这里没有看到提到的一个选项是使用矛线进行接收。这样,您就可以进行简单的哑阻塞等待,而不会(过多)干扰其他线程中的发送逻辑。
One option I haven't seen mentioned here would be to use a spearate thread for receives. That way you can make your simple dumb blocking waits without interfering (much) with your send logic in the other thread.