如何检测 TCP 套接字断开连接(使用 C Berkeley 套接字) [英] How to detect a TCP socket disconnection (with C Berkeley socket)

查看:44
本文介绍了如何检测 TCP 套接字断开连接(使用 C Berkeley 套接字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用循环从 c Berkeley 套接字读取消息,但我无法检测套接字何时断开连接,因此我将接受新连接.请帮忙

I am using a loop to read message out from a c Berkeley socket but I am not able to detect when the socket is disconnected so I would accept a new connection. please help

while(true) {
            bzero(buffer,256);
            n = read(newsockfd,buffer,255);
            printf("%s
",buffer);        
}

推荐答案

检测套接字已连接的唯一方法是写入套接字.

The only way you can detect that a socket is connected is by writing to it.

read()/recv() 上出现错误将表明连接已断开,但读取时未出现错误并不意味着连接已建立.

Getting a error on read()/recv() will indicate that the connection is broken, but not getting an error when reading doesn't mean that the connection is up.

您可能有兴趣阅读以下内容:http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html

You may be interested in reading this: http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html

此外,使用 TCP Keep Alive 可能有助于区分非活动状态和断开的连接(通过定期发送一些东西,即使应用程序没有要发送的数据).

In addition, using TCP Keep Alive may help distinguish between inactive and broken connections (by sending something at regular intervals even if there's no data to be sent by the application).

(删除了@Damon 指出的错误句子,谢谢.)

( Removed incorrect sentence as pointed out by @Damon, thanks.)

这篇关于如何检测 TCP 套接字断开连接(使用 C Berkeley 套接字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆