当客户端在 write() 期间终止连接时,由对等套接字错误重置连接

Connection reset by peer socket error when the client terminate connection during write()

本文关键字:连接 对等 套接字 错误 终止 write 客户端      更新时间:2023-10-16

>我让我的服务器向客户端(Web浏览器(发送了一个大文件,但是当我刷新页面时,我因对等错误而重置连接,程序终止。我期待的是服务器获得新的连接。

while (true)
{
check((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t *)&addrlen)),
"accept_failed");
read(new_socket, buffer_recv, 1024);
printf("%sn", buffer_recv);
T = std::thread(handle_connection, new_socket);
T.detach();
}

handle_connection包含

while (file.read(&buffer[0], 1024))
{
s = file.gcount();
content = chunk::make_chunk(buffer, s);
check(write(new_socket, &content[0], content.size()), "Write_error");
}

其中检查是简单的错误处理函数并返回字符串make_chunk。如何使服务器不退出并继续侦听连接,请回答我是套接字编程的新手

是的,您可以将send()MSG_NOSIGNAL一起使用,也可以使用setsockopt()设置SO_NOSIGPIPE套接字选项。但是,只需对现有代码进行最小的更改并将设置应用于所有创建的套接字,您可以执行以下操作:

write()的手册页

EPIPE: FD连接到读取端关闭的管道或插座。发生这种情况时,写入过程也将收到SIGPIPE信号。 (因此,仅当程序捕获、阻止或忽略此信号时,才会看到写入返回值。

#include <signal.h>
#include <stddef.h>
#include <unistd.h>
#include <errno.h>
int main()
{
/* .... */
sigset_t sigmask;
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGPIPE);
if (sigprocmask(SIG_BLOCK, &sigmask, NULL) != 0)  // get EPIPE instead
goto handle_sigprocmask_fail;
/* .... */
int wr_return = write(sockfd, buf, sizeof(buf));
if (wr_return == -1) {
if (errno == EPIPE)
goto handle_epipe;
}
}