1. 程式人生 > >TCP send函式會阻塞嗎?

TCP send函式會阻塞嗎?

很多學員在使用send函式的時候,發現send總是能正常返回,看起來好像是“非阻塞”,其實它是阻塞的,以下程式碼為證:

服務端:


#include <stdio.h>
#include <winsock2.h>  
#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 <winsock2.h>
#include <stdio.h>
#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阻塞解除了。