connect完成3次握手,非常耗时,怎么让connect减少超时等待引发的阻塞呢?
方法有:先设置为非阻塞,然后等待连接成功之后,重新设置回阻塞。
#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(默认为是阻塞socket)
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
// 设置为非阻塞的socket
int iMode = 1;
ioctlsocket(sockClient, FIONBIO, (u_long FAR*)&iMode);
// 定义服务端
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(8888);
// 超时时间
struct timeval tm;
tm.tv_sec = 5;
tm.tv_usec = 0;
int ret = -1;
// 连接服务端
if (-1 != connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)))
{
ret = 1; // 连接成功
}
else
{
fd_set set;
FD_ZERO(&set);
FD_SET(sockClient, &set);
if (select(-1, NULL, &set, NULL, &tm) <= 0)
{
ret = -1; // 有错误(select错误或者超时)
}
else
{
int error = -1;
int optLen = sizeof(int);
getsockopt(sockClient, SOL_SOCKET, SO_ERROR, (char*)&error, &optLen);
if (0 != error)
{
ret = -1; // 有错误
}
else
{
ret = 1; // 无错误
}
}
}
// 设回为阻塞socket
iMode = 0;
ioctlsocket(sockClient, FIONBIO, (u_long FAR*)&iMode); //设置为阻塞模式
// connect状态
printf("ret is %d\n", ret);
// 发送数据到服务端测试以下
if(1 == ret)
{
send(sockClient, "hello world", strlen("hello world") + 1, 0);
}
// 释放网络连接
closesocket(sockClient);
WSACleanup();
return 0;
}