多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 回响服务器 如果遇到 inet_addr函数错误 c/c++ -> 常规 -> SDL检查 -> 否 ![](https://img.kancloud.cn/52/3b/523b1eb89bebb90a074225f8f0b74b7a_1379x731.png) ### Server代码 ***** server.cpp ```c++ // Server.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <stdio.h> #include <WinSock2.h> #pragma comment (lib, "WS2_32.lib") #define BUF_SIZE 100 int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//INADDR_ANY表示任何IP sockAddr.sin_port = htons(1234); bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); listen(servSock, 20);//监听状态 SOCKADDR clntAddr;//接收客户端请求 int nSize = sizeof(SOCKADDR); SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); char buffer[BUF_SIZE]; //缓冲区 int strLen = recv(clntSock, buffer, BUF_SIZE, 0);//接收客户端发来的数据 //const char *str = "Hello World"; send(clntSock, buffer, strLen, NULL); closesocket(clntSock);//关闭套接字 closesocket(servSock); WSACleanup();//终止DLL; return 0; } ``` client.cpp ```c++ // Client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #include <WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") #define BUF_SIZE 100 int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET sock = socket(PF_INET, SOCK_STREAM, 0); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1234); connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); //connect之后可以进行输入 char bufSend[BUF_SIZE] = {0}; printf("Input a string :"); scanf("%s", bufSend); send(sock, bufSend, strlen(bufSend), 0); //接收服务器传回的数据 char szBuffer[MAXBYTE] = {0}; recv(sock, szBuffer, MAXBYTE, NULL); printf("Message from server: %s\n", szBuffer); closesocket(sock); WSACleanup(); system("pause"); return 0; } ```