服務端Server.c服務器
#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib") //加載 ws2_32.dll 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 *str = "Hello, I come from Mars.\n"; SOCKADDR clntAddr; SOCKET clntSock; for(;;) { clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); if(clntSock == INVALID_SOCKET) { printf("Failed accept().\n"); continue; } //向客戶端發送數據 send(clntSock, str, strlen(str)+sizeof(char), 0); } //關閉套接字 closesocket(clntSock); closesocket(servSock); //終止 DLL 的使用 WSACleanup(); return 0; }
客戶端Client.csocket
#include <stdio.h> #include <stdlib.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") 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 szBuffer[MAXBYTE] = {0}; int nRecv = recv(sock, szBuffer, MAXBYTE, 0); if(nRecv > 0) { szBuffer[nRecv] = '\0'; //輸出接收到的數據 printf("Message from server: %s\n", szBuffer); } //關閉套接字 closesocket(sock); //終止使用DLL WSACleanup(); printf("\nPress Enter to exit.\n"); getchar(); return 0; }