用C语言写一个只接受一个客户端连接的服务器程序
时间: 2024-09-07 21:04:15 浏览: 40
在C语言中,创建一个简单的单客户端连接的TCP服务器程序需要用到`socket`、`bind`、`listen`、`accept`和`close`等系统调用。以下是一个基本的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 12345
int main() {
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
char buffer[1024] = {0};
// 创建服务器套接字
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == -1) {
perror("Failed to create server socket");
return 1;
}
// 设置服务器地址和端口
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY; // 对于所有网络接口
// 绑定套接字到指定地址
if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Failed to bind server socket");
close(server_sock);
return 1;
}
// 监听等待连接
if (listen(server_sock, 1) < 0) {
perror("Failed to listen server socket");
close(server_sock);
return 1;
}
printf("Server is listening on port %d...\n", PORT);
// 接受客户端连接
while (true) {
client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &addr_len);
if (client_sock == -1) {
perror("Failed to accept client connection");
continue;
}
printf("Accepted connection from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
// 接收客户端数据
ssize_t bytes_received = recv(client_sock, buffer, sizeof(buffer), 0);
if (bytes_received > 0) {
buffer[bytes_received] = '\0';
printf("Received message: %s\n", buffer);
// 发送响应
send(client_sock, "Hello from server!", strlen("Hello from server!"), 0);
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
} else {
perror("Failed to receive data");
}
// 关闭客户端连接
close(client_sock);
}
// 关闭服务器套接字
close(server_sock);
return 0;
}
```
这个程序会在给定的端口(本例中是12345)上监听,当有客户端连接时,会接收客户端的消息并发送回复。注意,这个例子没有处理异常情况,实际应用中需要添加适当的错误检查。
阅读全文