包含头文件

1
2
#include <winsock2.h>
#include <stdio.h>

需要链接的库文件

1
ws2_32.lib

winsocket初始化

1
2
3
4
5
6
7
8
9
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
struct sockaddr_in serverAddr = { 0x00 };
struct sockaddr_in clientAddr = { 0x00 };
int clientAddrLen = sizeof(clientAddr);

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed.\n");
}

创建winsocket

1
2
3
4
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Socket failed.\n");
WSACleanup();
}

IP及端口号配置

1
2
3
4
5
6
7
8
9
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(9988);

if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("Bind failed.\n")
closesocket(serverSocket);
WSACleanup();
}

监听客户端连接

1
2
3
4
5
if (listen(serverSocket, 5) == SOCKET_ERROR) {
printf("Listen failed.\n");
closesocket(serverSocket);
WSACleanup();
}

接受客户端连接

1
2
3
4
5
if ((clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) == INVALID_SOCKET) {
printf("Accept failed.\n");
closesocket(serverSocket);
WSACleanup();
}

接收数据

1
int bytesReceived = recv(clientSocket, (char*)(_sRxBuffer + _sRxLenght), BUFFER_SIZE, 0);

发送数据

1
int txPacketlenght = send(socket, (const char*)_sTxBuffer, txPacketlenght, 0);

回收winsocket资源

1
2
3
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();

检查连接断开情形

1
2
3
4
5
6
7
8
9
10
11
int bytesReceived = recv(clientSocket, buffer, bufferSize, 0);
if (bytesReceived == 0) {
printf("Client socket disconnected gracefully.\n");
} else if (bytesReceived == SOCKET_ERROR) {
int error = WSAGetLastError();
if (error == WSAECONNRESET) {
printf("Client socket disconnected unexpectedly.\n");
} else {
printf("Recv failed with error: %d\n", error);
}
}

© 2025 hywing 使用 Stellar 创建
总访问 113701 次 | 本页访问 326