如何检测TCP套接字断开(以c伯克利插座) [英] how to detect a TCP socket disconnection (with c berkeley socket)

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

问题描述

我使用的是循环从C伯克利套接字中读取消息了,但我不能当插座断开,所以我会接受一个新的连接来检测。请大家帮忙

 ,而(真){
            bzero(缓冲液,256);
            N =读(newsockfd,缓冲器,255);
            的printf(%S \\ n,缓冲区);
}


解决方案

您可以检测一个套接字连接的唯一方法是通过写它。

获取有关阅读()一个错误/的recv()将指示连接中断,但阅读时没有收到错误消息并不意味着连接了。

您可能感兴趣的阅读本:
<一href=\"http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html\">http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html

此外,使用 TCP保持活动可以帮助无效,打破区分连接(用发送定期的东西,即使没有数据要由应用程序发送)。

(编辑:正如@Damon指出,删除不正确的句子,谢谢)

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\n",buffer);        
}

解决方案

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

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.

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

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).

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

这篇关于如何检测TCP套接字断开(以c伯克利插座)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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