ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 服务器 server.cpp ```c++ #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <WinSock2.h> #pragma comment(lib,"ws2_32.lib") int main(int argc, char * argv[]) { //创建套接字 WORD myVersionRequest; WSADATA wsaData; myVersionRequest = MAKEWORD(1,1); int err; err = WSAStartup(myVersionRequest, &wsaData); if (!err) { printf("已经打开套接字!\n"); } else { //进一步绑定套接字 printf("嵌套字未打开!"); return 0; } SOCKET serSocket = socket(AF_INET,SOCK_STREAM,0);//创建了可识别的套接字 //需要绑定的参数 SOCKADDR_IN addr; addr.sin_family = AF_INET;//ipv4 addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//INADDR_ANY表示任何IP addr.sin_port = htons(6000); bind(serSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));//绑定完成 listen(serSocket,5);//其中第二个参数代表能够接受的最多的连接数 //////////////// //开始监听 /////////////// SOCKADDR_IN clientSocket; int len = sizeof(SOCKADDR); while (1) { //如果这里不是accept而是conection的话,就会不断的监听 SOCKET serConn = accept(serSocket,(SOCKADDR*)&clientSocket,&len); char sendBuf[100]; sprintf(sendBuf,"welcome %s to socket",inet_ntoa(clientSocket.sin_addr));//找到对应ip并打印 send(serConn,sendBuf,strlen(sendBuf)+1,0); char receiveBuf[50];//接收 recv(serConn,receiveBuf,50,0); printf("%s\n",receiveBuf); closesocket(serConn);//关闭 } WSACleanup();//释放资源 不能写在循环里面 要不然会死循环 return 0; } ``` ## 客户端 client.cpp ````` #include <WinSock2.h> #include <stdio.h> #pragma comment(lib,"ws2_32.lib") int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(1, 1); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return 0; } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); return 0; } SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); send(sockClient, "hello", strlen("hello") + 1, 0); char recvBuf[50]; [win32t网络编程](socket网络编程.md) recv(sockClient, recvBuf, 50, 0); printf("%s\n", recvBuf); closesocket(sockClient); WSACleanup(); return 0; } ````