目录
1--Hello Word服务器端
2--客户端
3--编译运行
3-1--编译服务器端
3-2--编译客户端
3-3--运行
1--Hello Word服务器端
// gcc hello_server_win.c -o hello_server_win -lwsock32
// hello_server_win 9190
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>// 打印错误信息
void ErrorHandling(char* message){fputs(message, stderr);fputc('\n', stderr);exit(1);
}int main(int argc, char* argv[]){WSADATA wsaData;SOCKET hServSock, hClntSock;SOCKADDR_IN servAddr, clntAddr;int szClntAddr;char message[] = "Hello World!";if(argc != 2){printf("Usage: %s <port>\n", argv[0]);exit(1);}if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){ // 初始化套接字库ErrorHandling("WSAStartup() error!");}hServSock = socket(PF_INET, SOCK_STREAM, 0); // 创捷socketif(hServSock == INVALID_SOCKET){ErrorHandling("socket() error!");}memset(&servAddr, 0, sizeof(servAddr));servAddr.sin_family = AF_INET;servAddr.sin_addr.s_addr = htonl(INADDR_ANY);servAddr.sin_port = htons(atoi(argv[1])); // 端口if(bind(hServSock, (SOCKADDR*) &servAddr, sizeof(servAddr)) == SOCKET_ERROR){ // 给 socket 分配 ip 地址和端口号ErrorHandling("bind() error!");}if(listen(hServSock, 5) == SOCKET_ERROR){ // 置于listen状态,使socket可接收客户端连接请求ErrorHandling("listen() error!");}szClntAddr = sizeof(clntAddr);hClntSock = accept(hServSock, (SOCKADDR*)&clntAddr, &szClntAddr); // 使socket受理客户端的连接请求if(hClntSock == INVALID_SOCKET){ErrorHandling("accept() error!");}send(hClntSock, message, sizeof(message), 0); // 向连接的客户端发送数据closesocket(hClntSock);closesocket(hServSock);WSACleanup(); // 注销初始化的套接字库return 0;
}
2--客户端
// gcc hello_client_win.c -o hello_client_win -lwsock32
// hello_client_win 127.0.0.1 9190
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>// 打印错误信息
void ErrorHandling(char* message){fputs(message, stderr);fputc('\n', stderr);exit(1);
}int main(int argc, char* argv[]){WSADATA wsaData;SOCKET hSocket;SOCKADDR_IN servAddr;char message[30];int strLen;if(argc != 3){printf("Usage: %s <IP> <port>\n", argv[0]);exit(1);}if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){ // 初始化套接字库ErrorHandling("WSAStartup() error!"); }hSocket = socket(PF_INET, SOCK_STREAM, 0); // 创捷socketif(hSocket == INVALID_SOCKET){ErrorHandling("socket() error!");}memset(&servAddr, 0, sizeof(servAddr));servAddr.sin_family = AF_INET;servAddr.sin_addr.s_addr = inet_addr(argv[1]);servAddr.sin_port = htons(atoi(argv[2]));if(connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR){ // 向服务器端发送连接请求ErrorHandling("connect() error!");}strLen = recv(hSocket, message, sizeof(message) - 1, 0); // 接收服务器发来的数据if(strLen == -1){ErrorHandling("read() error!");}printf("Message from server: %s \n", message); closesocket(hSocket);WSACleanup(); // 注销初始化的Winsock库return 0;
}
3--编译运行
3-1--编译服务器端
gcc hello_server_win.c -o hello_server_win -lwsock32
3-2--编译客户端
gcc hello_client_win.c -o hello_client_win -lwsock32
3-3--运行
# 运行服务器端
hello_server_win 9190# 运行客户端
hello_client_win 127.0.0.1 9190
运行结果: