Winsock“recv”不会在非正常连接终止时返回
Posted
技术标签:
【中文标题】Winsock“recv”不会在非正常连接终止时返回【英文标题】:Winsock "recv" doesn't return on a non-graceful connection termination 【发布时间】:2021-11-19 01:34:13 【问题描述】:我正在运行以下代码:
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8081"
int __cdecl main(void)
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR)
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
while (true)
printf("Waiting for connection...\n");
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET)
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
else
printf("Received connection !\n");
// No longer need server socket
//closesocket(ListenSocket);
// Receive until the peer shuts down the connection
do
printf("Before recv\n");
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
printf("After recv\n");
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
recvbuf[iResult] = 0;
// Echo the buffer back to the sender
printf("%s\n", recvbuf);
else if (iResult == 0)
printf("Connection closing...\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
while (iResult > 0);
printf("After loop !!\n");
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
// cleanup
closesocket(ClientSocket);
//
// shutdown the connection since we're done
WSACleanup();
return 0;
当客户端不正常地终止连接时,即直接关闭而不调用 close()
或任何东西,recv()
函数将阻塞并且不会返回。
我在 recv 函数的文档中读到:
如果套接字是面向连接的,并且远程端已经优雅地关闭了连接,并且所有数据都已接收到,recv 将立即完成,接收到零字节。如果连接已被重置,recv 将失败并返回错误 WSAECONNRESET。
但事实并非如此。就我而言, recv() 只是阻止执行。我想文档指的是在对等方关闭连接后调用 recv() 的情况,但在我的情况下,在调用 recv() 后连接正在关闭。 我该如何处理?
【问题讨论】:
【参考方案1】:异常连接丢失(网络通信刚刚停止,而不是显式重置)需要时间让操作系统检测到它。 TCP 旨在在网络中断的情况下具有弹性。 recv()
最终将失败,但操作系统可能需要几分钟的时间在内部超时并使连接失效。在此之前,不会报告任何错误。
如果您不想等待操作系统使连接失效所需的时间,则必须在自己的代码中启用自己的超时,例如在recv()
之前调用select()
,或者通过使用setsockopt(SO_RCVTIMEO)
、WSAIoctl(SIO_KEEPALIVE_VALS)
等使recv()
超时退出。然后,如果超时,您可以关闭套接字。
【讨论】:
以上是关于Winsock“recv”不会在非正常连接终止时返回的主要内容,如果未能解决你的问题,请参考以下文章
Winsock recv() 无休止地收到 10053 WSAECONNABORTED 错误