[C++] 纯文本查看 复制代码 DWORD start_time = GetTickCount();
SOCKET connectSocket = INVALID_SOCKET;
CString szFormat;
do {
// 创建socket
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET) {
szFormat.Format(_T("socket函数出现错误: %ld"), WSAGetLastError());
break;
}
// socket设置为非阻塞
unsigned long on = 1;
if (ioctlsocket(connectSocket, FIONBIO, &on) < 0) {
szFormat = _T("设置ioctlsocket失败");
break;
}
// 尝试连接
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.S_un.S_addr = pDlg->Resolve(chTarget);
clientService.sin_port = htons(static_cast<u_short>(_ttoi(Port)));
int ret = connect(connectSocket, (struct sockaddr*)&clientService, sizeof(clientService));
if (ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) {
szFormat.Format(_T("连接错误: %ld"), WSAGetLastError());
break;
}
fd_set writeset;
FD_ZERO(&writeset);
FD_SET(connectSocket, &writeset);
timeval tv;
tv.tv_sec = iTimeOut;
tv.tv_usec = 0;
time_t t1 = time(NULL);
ret = select(connectSocket + 1, NULL, &writeset, NULL, &tv);
time_t t2 = time(NULL);
if (ret == 0) {
szFormat.Format(_T("超时%d s"), static_cast<int>(t2 - t1));
}
else if (ret < 0) {
szFormat.Format(_T("连接错误%ld"), WSAGetLastError());
}
else {
DWORD end_time = GetTickCount();
szFormat.Format(_T("%d ms"), end_time - start_time);
}
} while (false);
// 确保每次操作后关闭socket
if (connectSocket != INVALID_SOCKET) {
closesocket(connectSocket);
}
|