服務端: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; }