服务端骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <windows.h>int main()
{WORD wVersionRequested = MAKEWORD(2, 2);WSADATA WSAData;WSAStartup(wVersionRequested, &WSAData);//本程序创建一个TCP套接字SOCKET socScrver = socket(AF_INET, SOCK_STREAM,0);//准备一个服务器地址结构体,指定服务器监听的端口(8000)SOCKADDR_IN socSrv{ 0 };socSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//接受来自任何IP地址的连接socSrv.sin_family = AF_INET;socSrv.sin_port = 8000;//将本程序的套接字与服务器地址\端口绑定bind(socScrver, (sockaddr*)&socSrv, sizeof(SOCKADDR_IN));//使套接字进入监听状态,准备接受客户端的连接请求listen(socScrver, SOMAXCONN);sockaddr addr;UINT length = sizeof(sockaddr);while (TRUE){//服务端进入连接等待状态,如果有连接,accept函数会返回一个新的套接字接口sockConn,该接口代表了与客户端建立的连接。SOCKET sockConn = accept(socScrver, &addr, &length);//通过这个连接状态套接字接口,发送消息send(sockConn, "I am Server", strlen("I am Server") + 1, NULL);CHAR ClientBuffer[MAX_PATH] = { 0 };//通过这个连接状态套接字接口,接受消息recv(sockConn, ClientBuffer, sizeof(ClientBuffer) / sizeof(CHAR), 0);printf("客户端消息:%s\n", ClientBuffer);//关闭连接状态套接字接口closesocket(sockConn);}//清理closesocket(socScrver);WSACleanup();system("pause");return 0;
}
客服端骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <windows.h>int main()
{WORD wVersionRequested = MAKEWORD(2, 2);WSADATA WSAData;WSAStartup(wVersionRequested, &WSAData);//本程序创建一个TCP套接字SOCKET socClient = socket(AF_INET, SOCK_STREAM, 0);//指定一个服务器地址,指定服务器监听的端口SOCKADDR_IN socSrv{ 0 };socSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");socSrv.sin_family = AF_INET;socSrv.sin_port = 8000;//服务器与我的套接字建立连接(发送连接请求)connect(socClient, (sockaddr*)&socSrv, sizeof(SOCKADDR_IN));//接受服务器端的消息CHAR ClientBuffer[MAX_PATH] = { 0 };recv(socClient, ClientBuffer, sizeof(ClientBuffer) / sizeof(CHAR), 0);printf("服务端消息:%s\n", ClientBuffer);//给服务器端的发送消息send(socClient, "I am Client", strlen("I am Client") + 1, NULL);//清理closesocket(socClient);WSACleanup();system("pause");return 0;
}