在C语言中进行网络编程,主要使用socket库来创建和操作网络连接。以下是一个简单的TCP服务器和客户端的示例代码,展示了如何进行网络编程:
服务器端代码
```c
include include include include include include define PORT 8080 define BUFFER_SIZE 1024 int main() { int serverSocket, clientSocket; struct sockaddr_in serverAddress, clientAddress; char buffer[BUFFER_SIZE]; int addrLen = sizeof(clientAddress); // 创建套接字 if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket failed"); exit(EXIT_FAILURE); } // 设置服务器地址 serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(PORT); // 绑定套接字到服务器地址 if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) { perror("bind failed"); exit(EXIT_FAILURE); } // 监听连接 if (listen(serverSocket, 5) == -1) { perror("listen"); exit(EXIT_FAILURE); } printf("Server is listening on port %d\n", PORT); // 接受客户端连接 if ((clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, (socklen_t *)&addrLen)) == -1) { perror("accept"); exit(EXIT_FAILURE); } // 读取并输出客户端发送的数据 read(clientSocket, buffer, BUFFER_SIZE); printf("Client message: %s\n", buffer); // 向客户端发送数据 send(clientSocket, "Hello from server!", strlen("Hello from server!"), 0); printf("Message sent to client\n"); // 关闭套接字 close(clientSocket); close(serverSocket); return 0; } ``` 客户端代码 ```c include include include include include include define PORT 8080 define BUFFER_SIZE 1024 int main() { int clientSocket; struct sockaddr_in serverAddress; char buffer[BUFFER_SIZE]; // 创建套接字 if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket failed"); exit(EXIT_FAILURE); } // 设置服务器地址 serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddress.sin_port = htons(PORT); // 连接到服务器 if (connect(clientSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) { perror("connect"); exit(EXIT_FAILURE); } // 向服务器发送数据 send(clientSocket, "Hello from client!", strlen("Hello from client!"), 0); printf("Message sent to server\n"); // 读取并输出服务器发送的数据 read(clientSocket, buffer, BUFFER_SIZE); printf("Server message: %s\n", buffer); // 关闭套接字 close(clientSocket); return 0; } ``` 编译和运行 1. 将上述代码分别保存为`server.c`和`client.c`。 2. 在Linux系统中,使用以下命令编译代码: ```sh gcc server.c -o server gcc client.c -o client ``` 3. 运行服务器端程序: