TCP send函数会阻塞吗?

很多学员在使用send函数的时候,发现send总是能正常返回,看起来好像是“非阻塞”,其实它是阻塞的,以下代码为证:


服务端:

 


#include 
#include   
#pragma comment(lib, "ws2_32.lib")  

int main()
{
	WORD wVersionRequested; 
	WSADATA wsaData;   
	wVersionRequested = MAKEWORD(2, 2);  
	 
	WSAStartup(wVersionRequested, &wsaData);
	 
    SOCKET   s  = socket(AF_INET, SOCK_STREAM, 0);

	SOCKADDR_IN addrSrv;

	addrSrv.sin_family = AF_INET;  
	addrSrv.sin_addr.S_un.S_addr = INADDR_ANY;  
	addrSrv.sin_port = htons(22222); 
 
	bind(s, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
	 
	listen(s, 5);
	 
	SOCKADDR_IN addrClient;
	int len = sizeof(SOCKADDR);
	SOCKET  c= accept(s, (SOCKADDR*)&addrClient, &len);
	printf("客户端链接上了\n");
	while (true)
	{
		getchar();
		char szRecvBuf[1024 * 16] = { 0 };
		int  ret=recv(c, szRecvBuf, sizeof(szRecvBuf), 0);
		printf("ret is %d, error is %d\n", ret, GetLastError());
	}

	closesocket(c);
	closesocket(s);
	WSACleanup();

	return 0;
}

客户端:

#include 
#include 
#pragma comment(lib, "ws2_32.lib")

int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD(2, 2);

	WSAStartup(wVersionRequested, &wsaData);

	SOCKET s= socket(AF_INET, SOCK_STREAM, 0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(22222);
	connect(s, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));

	while (1)
	{
		getchar();
		char szSend[1024*16] = { 0 };
		int ret = send(s, szSend, sizeof(szSend), 0);
		printf("ret is %d, error is %d\n", ret, GetLastError());
	}

	closesocket(s);
	WSACleanup();

	return 0;
}

测试方法:

1. 先运行服务端,再运行客户端。

2. 在客户端一直敲回车键,让客户端一直Send, 多次操作后,发现不打印信息了,说明send已经阻塞。

3.此时在服务端敲回车键,发现收到客户端的数据,多次操作后,发现不打印信息了,说明已经无数据可接收。

4.此时在客户端敲,发现又可以发送了,说明Send阻塞解除了。

TCP send函数会阻塞吗?_第1张图片

 

你可能感兴趣的:(网络)