gpt4 book ai didi

C套接字关闭检测

转载 作者:行者123 更新时间:2023-11-30 16:09:38 25 4
gpt4 key购买 nike

我正在阅读这篇关于 How to detect when the client closes the connection 的文章

但是当我运行这篇文章中的代码时(将其粘贴在下面):

fd = accept(listenSocket);
pid_t childProcess = fork();
if (childProcess == (pid_t)-1) {
perror("Unable to create new process for client connection");
exit(1);
}
else if (childProcess == 0) {
// read from socket, process queries, etc.
}
else {
// use the poll system call to be notified about socket status changes
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN | POLLHUP | POLLRDNORM;
pfd.revents = 0;
while (pfd.revents == 0) {
// call poll with a timeout of 100 ms
if (poll(&pfd, 1, 100) > 0) {
// if result > 0, this means that there is either data available on the
// socket, or the socket has been closed
char buffer[32];
if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
// if recv returns zero, that means the connection has been closed:
// kill the child process
kill(childProcess, SIGKILL);
waitpid(childProcess, &status, WNOHANG);
close(fd);
// do something else, e.g. go on vacation
}
}
}
}

当客户端断开连接时,上述逻辑(在服务器端)根本不会遇到最后一个 else 语句。因此逻辑实际上不可能检测到断开连接。

现在这个帖子对于套接字断开连接检测来说正确吗?

最佳答案

我在linux下使用

#include <sys/socket.h>

我的检测已经工作了很多年。套接字是一个服务器。通过recv的返回码进行检测。

...
cl = accept (sock, (struct sockaddr *) &sock_clnt, (socklen_t *) &len);
unsigned char c;
for (;;)
{
int ret = recv (cl, &c, 1, MSG_DONTWAIT);

if (ret == 1)
{
// 1 byte received
..
}
else if (ret == -1) // socket open but no data
{
// socket open but no data
...
}
else
{
// ret = 0, socket opened but now client left
...
}
// sleep
...
}
...

关于C套接字关闭检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com