tcp client 如何检测断开连接

发布于 2019-11-15 17:32:46    浏览:761
tcp client与server连接成功后,如果由于各种原因,如网线断开,server关闭,client端如何检测连接断开?

查看更多

1 个回答
flyboy
flyboy 2019-11-15
This guy hasn't written anything yet
楼主可以搜索一下 keepalive 相关资料,下面的代码是一段配置 keepalive 属性的代码供楼主参考。


rt_err_t socket_config(void)
{
int keepalive = 1; //Enable keepalive.
int keepidle = 60; //idle time is 60s.
int keepinterval = 5; //sending interval of detective packet
int keepcount = 3; //detective count.

int flag = 1;

if (setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(keepalive)) < 0)
{
LOG("set Keep-Alive attribute failed\n");
return -RT_ERROR;
}
setsockopt(socket_fd, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&keepidle , sizeof(keepidle));
setsockopt(socket_fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepinterval , sizeof(keepinterval));
setsockopt(socket_fd, IPPROTO_TCP, TCP_KEEPCNT, (void *)&keepcount , sizeof(keepcount));

setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, (void *)&flag , sizeof(flag));

return RT_EOK;
}


下载附件[keepalive.c]

撰写答案

请登录后再发布答案,点击登录
关注者
0
被浏览
761

发布
问题

分享
好友

手机
浏览

扫码手机浏览