💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
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); char buffer[BUF_SIZE]; //缓冲区 while (1) { SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); int strLen = recv(clntSock, buffer, BUF_SIZE, 0);//接收客户端发来的数据 send(clntSock, buffer, strLen, NULL); closesocket(clntSock); //关闭套接字 memset(buffer, 0, BUF_SIZE); //重置缓冲区 } closesocket(servSock); WSACleanup();//终止DLL; return 0; } ``` client.cpp ``` // 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); 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之后可以进行输入 char bufSend[BUF_SIZE] = { 0 }; char bufRecv[BUF_SIZE] = { 0 }; while (1) { SOCKET sock = socket(PF_INET, SOCK_STREAM, 0); connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); printf("Input a string :"); scanf("%s", bufSend); send(sock, bufSend, strlen(bufSend), 0); //接收服务器传回的数据 recv(sock, bufRecv, BUF_SIZE, NULL); printf("Message from server: %s\n", bufRecv); memset(bufSend, 0, BUF_SIZE); //重置缓冲区 memset(bufRecv, 0, BUF_SIZE); //重置缓冲区 closesocket(sock); } WSACleanup(); return 0; } ```