帮我写一个TCP服务端的C语言代码
时间: 2023-06-18 08:04:31 浏览: 91
好的,这是一个简单的 TCP 服务端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define MAX_CLIENTS 5
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int server_socket, client_socket;
struct sockaddr_in server_address;
int opt = 1;
int addrlen = sizeof(server_address);
char buffer[BUFFER_SIZE] = {0};
// 创建 socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置 socket 选项,使服务端可以重新绑定端口
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// 填充服务端地址信息
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
// 绑定 socket 到服务端地址
if (bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听客户端连接请求
if (listen(server_socket, MAX_CLIENTS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("TCP server listening on port %d\n", PORT);
// 接收客户端连接请求
if ((client_socket = accept(server_socket, (struct sockaddr *) &server_address, (socklen_t *) &addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("Accepted connection from client\n");
// 接收客户端发送的数据
int valread = read(client_socket, buffer, BUFFER_SIZE);
printf("Received message from client
阅读全文