如何检测客户端仍连接(而不是挂时)使用的recv()? [英] How to detect that the client is still connected (and not hung-up) using recv()?

查看:158
本文介绍了如何检测客户端仍连接(而不是挂时)使用的recv()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个多客户服务器程序的 C对 SuSE Linux企业服务器12.3(x86_64的),我使用的每个客户端一个线程来接收数据即可。

I have written a multiclient Server program in C on SuSE Linux Enterprise Server 12.3 (x86_64), I am using one thread per client to receive data.

我的问题是:结果
我使用一个终端运行服务器,并使用其他几个终端远程登录到我的服务器(作为客户端)。我已经使用的recv()在服务器从客户端接收数据时,我还申请检查)的返回值的recv(即对错误 1 ;康涅狄格州逢 0 &放大器。其他正常运行。我没有使用任何标志在的recv()

My problem is:
I am using one terminal to run the server, and using several other terminals to telnet to my server (as client). I have used recv() in the server to receive data from client, I have also applied checks for return value of recv() i.e. Error on -1; Conn. Closed on 0 & Normal operation else. I have not used any flags in recv().

我的程序工作正常,如果我只是关闭Telnet会话通常使用(即断开客户机)按Ctrl +] 关闭,但如果我强行终止使用杀&LT客户; PID> 然后我的服务器是无法检测到连接丢失。

My program works fine if I just close the telnet session (i.e. disconnect client) normally using Ctrl+] and close, but if I forcefully terminate the client using kill <pid> then my server is unable to detect loss of connection.

如何解决呢?

约束:我不希望把条件对客户端,我想解决这个问题在服务器端只

Constraint: I do not want to put condition on client side, I want to fix this on server side only.

推荐答案

您可以在您的服务器套接字上启用 SO_KEEPALIVE

You can enable SO_KEEPALIVE on the socket in your server.

/* enable keep-alive on the socket */
int one = 1;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));

在默认情况下,保持活动启动时,连接具有保持活动状态的探测尝试之前,闲置2小时。您可以调整保持活跃时间是一个小更积极通过调整 TCP_KEEPIDLE 参数:

int idletime = 120; /* in seconds */
setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &idletime, sizeof(idletime));

当被发送的探测,它期望从另一端的确认。如果有一个确认,探针直到空闲计时器再次期满保持沉默。保活探针再次重试,在默认情况下每75秒,如果没有接收到确认到探针。这可以用 TCP_KEEPINTVL 选项进行调整。在 TCP_KEEPCNT 选项控制许多连续的失败如何触发的连接被丢弃。默认情况下,这个数字是9。

When a probe is sent, it expects an acknowledgement from the other end. If there is an acknowledgement, the probe stays silent until the idle timer expires again. The keep-alive probe is retried again, by default every 75 seconds, if no acknowledgement to the probe is received. This can be adjusted with the TCP_KEEPINTVL option. The TCP_KEEPCNT option controls how many successive failures triggers the connection to be dropped. By default, that number is 9.

这些选项都可以在Linux上。 BSD也有类似的选项,但名称不同。

These options are available on Linux. BSD has similar options, but are named differently.

这篇关于如何检测客户端仍连接(而不是挂时)使用的recv()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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