在windows中用C++实现:server端TCP通讯,当client端通讯中断,server端重新监听
时间: 2024-05-02 08:22:55 浏览: 149
C++实现Tcp客户端和服务器端的通信
您可以使用以下代码实现在Windows中使用C语言实现server端TCP通讯,在client端通讯中断时,server端重新监听:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET listenSock, clientSock;
struct sockaddr_in listenAddr, clientAddr;
int clientLen, ret;
// 初始化Winsock库
ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (ret != 0) {
printf("WSAStartup failed: %d\n", ret);
return 1;
}
// 创建server端socket
listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSock == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 绑定server端socket到地址
listenAddr.sin_family = AF_INET;
listenAddr.sin_addr.s_addr = htonl(INADDR_ANY);
listenAddr.sin_port = htons(12345);
ret = bind(listenSock, (struct sockaddr *)&listenAddr, sizeof(listenAddr));
if (ret == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
closesocket(listenSock);
WSACleanup();
return 1;
}
// 监听client的连接请求
ret = listen(listenSock, 5);
if (ret == SOCKET_ERROR) {
printf("listen failed: %d\n", WSAGetLastError());
closesocket(listenSock);
WSACleanup();
return 1;
}
// 等待client的连接
clientLen = sizeof(clientAddr);
clientSock = accept(listenSock, (struct sockaddr *)&clientAddr, &clientLen);
if (clientSock == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(listenSock);
WSACleanup();
return 1;
}
// 收到client的连接请求后开始通讯,这里不再赘述...
// 循环监听client的连接,当client连接中断时重新监听
while (1) {
ret = recv(clientSock, buffer, sizeof(buffer), 0);
if (ret == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(clientSock);
closesocket(listenSock);
WSACleanup();
return 1;
}
else if (ret == 0) {
printf("Connection closed.\n");
closesocket(clientSock);
Sleep(1000); // 延迟1秒钟再重新监听,防止CPU占用率过高
clientLen = sizeof(clientAddr);
clientSock = accept(listenSock, (struct sockaddr *)&clientAddr, &clientLen);
if (clientSock == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(listenSock);
WSACleanup();
return 1;
}
printf("Connection re-established.\n");
}
else {
// 处理client发来的数据
printf("Received data: %s\n", buffer);
}
}
}
```
注意:以上代码仅作演示用途,还需要进行错误处理和添加适当的逻辑,以确保程序的正确性和稳定性。
阅读全文