包含头文件
1 |
需要链接的库文件
1 | ws2_32.lib |
winsocket初始化
1 | WSADATA wsaData; |
创建winsocket
1 | if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { |
IP及端口号配置
1 | serverAddr.sin_family = AF_INET; |
监听客户端连接
1 | if (listen(serverSocket, 5) == SOCKET_ERROR) { |
接受客户端连接
1 | if ((clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) == INVALID_SOCKET) { |
接收数据
1 | int bytesReceived = recv(clientSocket, (char*)(_sRxBuffer + _sRxLenght), BUFFER_SIZE, 0); |
发送数据
1 | int txPacketlenght = send(socket, (const char*)_sTxBuffer, txPacketlenght, 0); |
回收winsocket资源
1 | closesocket(clientSocket); |
检查连接断开情形
1 | int bytesReceived = recv(clientSocket, buffer, bufferSize, 0); |