服务端代码:
#include <windows.h> #include <stdio.h> #pragma comment(lib, "Ws2_32.lib") int main() { WSADATA WSAData; int ret = WSAStartup(MAKEWORD(1, 1), &WSAData); if(ret) { printf("WSAStartup failed: %d", ret); return 1; } printf("Current version: %d.%d/n", LOBYTE(WSAData.wVersion), HIBYTE(WSAData.wVersion)); printf("Highest version: %d.%d/n", LOBYTE(WSAData.wHighVersion), HIBYTE(WSAData.wHighVersion)); SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN)); listen(sockSrv, 5); SOCKADDR_IN addrClient; int addrLen = sizeof(SOCKADDR_IN); while(1) { SOCKET socketConn = accept(sockSrv, (LPSOCKADDR)&addrClient, &addrLen); char sendBuff[100]; sprintf_s(sendBuff, "Welcome! Your address is %s.", inet_ntoa(addrClient.sin_addr)); send(socketConn, sendBuff, strlen(sendBuff) + 1, 0); char recvBuff[100]; recv(socketConn, recvBuff, 100, 0); printf("Receive from %s: %s/n", inet_ntoa(addrClient.sin_addr), recvBuff); closesocket(socketConn); } WSACleanup(); return 0; }
客户端代码:
#include <windows.h> #include <stdio.h> #pragma comment(lib, "Ws2_32.lib") int main() { WSADATA WSAData; int ret = WSAStartup(MAKEWORD(1, 1), &WSAData); if(ret) { printf("WSAStartup failed: %d", ret); return 1; } printf("Current version: %d.%d/n", LOBYTE(WSAData.wVersion), HIBYTE(WSAData.wVersion)); printf("Highest version: %d.%d/n", LOBYTE(WSAData.wHighVersion), HIBYTE(WSAData.wHighVersion)); SOCKET socketClient = 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(socketClient, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN)); char recvBuff[100]; recv(socketClient, recvBuff, 100, 0); printf("Received: %s/n", recvBuff); char sendBuff[100]; sprintf_s(sendBuff, "Hello!"); send(socketClient, sendBuff, strlen(sendBuff) + 1, 0); closesocket(socketClient); WSACleanup(); return 0; }
服务器端程序:
1、创建套接字(socket)。
2、将套接字绑定到一个本地地址和端口上(bind)。
3、将套接字设为监听模式,准备接收客户请求(listen)。
4、等待客户请求到来;当请求到来后,接受连接请求,返回一个新的对应于此次连接的套接字(accept)。
5、用返回的套接字和客户端进行通信(send/recv)。
6、返回,等待另一客户请求。
7、关闭套接字。
客户端程序:
1、创建套接字(socket)。
2、向服务器发出连接请求(connect)。
3、和服务器端进行通信(send/recv)。
4、关闭套接字。