WinSock2的简单通信例子
Posted tntbomb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WinSock2的简单通信例子相关的知识,希望对你有一定的参考价值。
Server端:
#include <iostream> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") int main() { // 初始化Winsock 2.2 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { printf("WSAStartup ERROR "); } // 创建服务器的SOCKET对象 SOCKET connServer; connServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connServer == INVALID_SOCKET) { printf("ConnectServer ERROR "); } // 绑定地址和端口 SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addr.sin_port = 9999; int errCode = bind(connServer, (SOCKADDR*)&addr, sizeof(addr)); if (errCode == SOCKET_ERROR) { printf("Bind ERROR "); return 0; } // listen 监听 errCode = listen(connServer, 1); if (errCode == SOCKET_ERROR) { printf("Listen ERROR "); return 0; } // 声明和初始化变量 SOCKET acceptSocket; // 执行accept函数后新建用于实际通信的套接字 int lenSocket = sizeof(acceptSocket); SOCKADDR_IN clientSocket; int lenClinet = sizeof(clientSocket); int bytesRecv = SOCKET_ERROR; char sendbuf[64] = ""; char recvbuf[64] = ""; acceptSocket = accept(connServer, (SOCKADDR*)&clientSocket, &lenClinet); // 循环 while (true) { recv(acceptSocket, recvbuf, 64, 0); printf("Client: %s ", recvbuf); std::cout << "Server: "; std::cin >> sendbuf; send(acceptSocket, sendbuf, strlen(sendbuf), 0); } return 0; }
Client端:
#include <iostream> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") int main() { // 初始化WinSock WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("初始化出错! "); } // 创建连接到服务器的SOCKET对象 SOCKET ConnectSocket; ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ConnectSocket == INVALID_SOCKET) { printf("Error at socket()%ld ", WSAGetLastError()); WSACleanup(); return 0; } // 构建地址信息 sockaddr_in clientService; clientService.sin_family = AF_INET; clientService.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); clientService.sin_port = 9999; // 连接到服务器 if (connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR) { printf("Failed to connect. "); WSACleanup(); return 0; } printf("连接成功!!! "); // 声明和初始化变量 char sendbuf[64] = "Client: Sending data. "; char recvbuf[64] = ""; // 发送数据 while (true) { // 发送数据 std::cout << "Client: "; std::cin >> sendbuf; send(ConnectSocket, sendbuf, strlen(sendbuf), 0); // 接受数据 recv(ConnectSocket, recvbuf, 64, 0); printf("Server: %s ", recvbuf); } if (WSACleanup() == SOCKET_ERROR) { printf("清理错误 "); } return 0; }
Tips:先客户端发消息,服务端才能发送。也就是一问一答形式。
以上是关于WinSock2的简单通信例子的主要内容,如果未能解决你的问题,请参考以下文章