gpt4 book ai didi

c - 为什么 TCP 服务器套接字意外关闭?

转载 作者:行者123 更新时间:2023-11-30 19:41:03 25 4
gpt4 key购买 nike

我创建了一个 Win32 服务器-客户端应用程序,其中许多客户端连接到单个服务器,发送查询和接收响应。

它在许多安装中工作正常,但在其他一些安装中连接被关闭。客户端和服务器均报告连接已被远程主机关闭。连接创建后的socket操作顺序是这样的:

Client: sends query Q1 (by calling send)
Server: recvs query Q1 and sends R1
Client: recvs R1
Client: sends query Q2
Server: recvs query Q2 and sends R2
Client: recvs R2
and so on

在某些网络中,经过一段时间后,例如 1 小时或 10 分钟,

    Client: Sends Q(n) successfully
Server: recvs SOCKET_ERROR and my code exits thread.
//unexpected
WSAGetLastError() at server returns 10054: An existing connection was forcibly closed by the remote host.
Client: recvs SOCKET_ERROR.
WSAGetLastError() at client also returns 10054

在服务器中,每个客户端都有一个线程。服务器在响应之前的延迟可以忽略不计。

为什么服务器端的函数recv()会返回SOCKET_ERROR?谁关闭套接字?编辑:我更新了问题并放置了 WSAGetLastErrorCode() 返回值。为什么-1?这个问题有什么问题吗?

最佳答案

正如文档中所说

https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx

10054错误

Connection reset by peer.

An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

当您收到此错误时,您可能正在退出程序,因此请检查该错误并执行逻辑以从客户端列表或您可能拥有的其他结构中删除客户端并完成其线程,但您不需要关闭套接字。

这是recv()返回值文档

Return value

If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

关于c - 为什么 TCP 服务器套接字意外关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996762/

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