服务端:serverEcho.c
#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll #define BUF_SIZE 100 int main(int argc, char *argv[]){ //初始化 DLL WSADATA wsaData; WSAStartup( MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(servSock == INVALID_SOCKET) { printf("Failed socket().\n"); WSACleanup(); return 0; } //绑定套接字 struct sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; //使用IPv4地址 sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址 sockAddr.sin_port = htons(1234); //端口 if(bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == SOCKET_ERROR) { printf("Failed bind().\n"); WSACleanup(); return 0; } //进入监听状态 listen(servSock, 20); //循环接收客户端请求 int nSize = sizeof(SOCKADDR); char buffer[BUF_SIZE];//缓冲区 SOCKADDR clntAddr; SOCKET clntSock; for(;;) { clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); int strLen = recv(clntSock, buffer, BUF_SIZE, 0);//接收客户端发来的数据 if(clntSock == INVALID_SOCKET) { printf("Failed accept().\n"); continue; } //将客户端发送数据原样返回 send(clntSock, buffer, strLen, 0); } //关闭套接字 closesocket(clntSock); closesocket(servSock); //终止 DLL 的使用 WSACleanup(); return 0; }
客户端clienEcho.c
#include <stdio.h> #include <stdlib.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define BUF_SIZE 100 int main(int argc, char *agrv[]) { //初始化DLL WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); //创建套接字 SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock == INVALID_SOCKET) { printf("Failed socket().\n"); WSACleanup(); return 0; } //向服务器发起请求 struct sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1234); if(connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == -1) { printf("Failed connect().\n"); WSACleanup(); return 0; } //获取用户输入的字符串并发送给服务器 char bufSend[BUF_SIZE] = {0}; printf("Input a string: "); gets(bufSend); send(sock, bufSend, strlen(bufSend), 0); //接收服务器传回的数据 char bufRecv[BUF_SIZE] = {0}; int nRecv = recv(sock, bufRecv, BUF_SIZE, 0); if(nRecv > 0) { bufRecv[nRecv] = '\0'; //输出接收到的数据 printf("Message from server: %s\n", bufRecv); } //关闭套接字 closesocket(sock); //终止使用DLL WSACleanup(); return 0; }