要检查客户端是否通过C++中的Winsock断开连接,可以使用以下方法:
recv()
函数检查连接状态。recv()
函数是一个阻塞函数,当连接断开时,它会返回0。示例代码如下:#include <winsock2.h>
#include<iostream>
int main()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
std::cout << "WSAStartup failed: " << iResult<< std::endl;
return 1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
std::cout << "socket failed: " << WSAGetLastError()<< std::endl;
WSACleanup();
return 1;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(8080);
if (connect(sock, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
std::cout << "connect failed: " << WSAGetLastError()<< std::endl;
closesocket(sock);
WSACleanup();
return 1;
}
char buf[1024];
int recv_len = recv(sock, buf, sizeof(buf), 0);
if (recv_len == 0) {
std::cout << "Client disconnected"<< std::endl;
} else if (recv_len == SOCKET_ERROR) {
std::cout << "recv failed: " << WSAGetLastError()<< std::endl;
} else {
std::cout << "Received data: "<< std::string(buf, recv_len)<< std::endl;
}
closesocket(sock);
WSACleanup();
return 0;
}
select()
函数检查连接状态。select()
函数可以检查一个或多个套接字的状态,当连接断开时,它会返回一个错误代码。示例代码如下:#include <winsock2.h>
#include<iostream>
int main()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
std::cout << "WSAStartup failed: " << iResult<< std::endl;
return 1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
std::cout << "socket failed: " << WSAGetLastError()<< std::endl;
WSACleanup();
return 1;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(8080);
if (connect(sock, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
std::cout << "connect failed: " << WSAGetLastError()<< std::endl;
closesocket(sock);
WSACleanup();
return 1;
}
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
int select_result = select(0, &readfds, NULL, NULL, &timeout);
if (select_result == SOCKET_ERROR) {
std::cout << "select failed: " << WSAGetLastError()<< std::endl;
} else if (select_result == 0) {
std::cout << "Client disconnected"<< std::endl;
} else {
char buf[1024];
int recv_len = recv(sock, buf, sizeof(buf), 0);
if (recv_len == SOCKET_ERROR) {
std::cout << "recv failed: " << WSAGetLastError()<< std::endl;
} else {
std::cout << "Received data: "<< std::string(buf, recv_len)<< std::endl;
}
}
closesocket(sock);
WSACleanup();
return 0;
}
以上两种方法都可以用于检查客户端是否通过Winsock断开连接。
GAME-TECH
“中小企业”在线学堂
原引擎 | 场景实战系列
小程序·云开发官方直播课(数据库方向)
云+社区技术沙龙[第7期]
云+社区技术沙龙[第6期]
GAME-TECH
云+社区技术沙龙[第17期]
领取专属 10元无门槛券
手把手带您无忧上云