如何检测本地主机关闭的连接?
我用 C 语言编写了 TCP 客户端和服务器。这些软件仅在同一台计算机上运行。
1) 我的 TCP 客户端向服务器 (localhost) 发送命令。
2)服务器努力工作并给出响应。
问题是,如果 TCP 客户端关闭连接,我无法检测到客户端连接已关闭,而服务器将执行长时间的工作。我只能用 SEND 函数检测到这一点,但为时已晚,因为服务器已经工作了。
我知道如果机器是远程的,那么进行这种检测一定非常困难。就我而言,它是同一台机器,这应该使任务更容易,但我还没有找到解决方案......可以使用选择功能吗?
感谢您。
I have write a TCP client and server in C. These software run on the same computer ONLY.
1) My TCP client send a command to the server (localhost).
2) The server works hard and give a response.
The problem is if the TCP Client closes the connection, I am unable to detect a client connection closed WHILE server is going to do its long work. I can only detect this with the SEND function, but it's too late because the server have already work.
I understand that this must be very hard to make this detection if the machines are remote. In my case, it is the same machine, which should make the task easier, but I have not found a solution ... Can be with the select function?
Thanks you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
select
来完成此操作,如下所示:select
读取套接字上的事件。因此,当套接字可读时,select
解除阻塞当select
将解除阻塞,并且recv
将读取 0 个字节。如果是这样,你可以停止工作线程You can do it with
select
like this:select
for read events on the socket. Soselect
unblocks when the socket is readableselect
will unblock andrecv
will read 0 bytes. If so, you can stop the worker thread