【Linux】手把手教你实现udp服务器
在Linux环境下,我们可以使用C语言来编写一个简单的UDP服务器。以下是一个基本的UDP服务器实现的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#define BUFF_LEN 1024
#define SERVER_PORT 8080
int main() {
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t client_len;
int server_fd;
char buffer[BUFF_LEN];
// 创建socket
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址结构
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(SERVER_PORT);
// 绑定socket到服务器地址
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Server is running on port %d\n", SERVER_PORT);
printf("Waiting for messages...\n");
while (1) {
client_len = sizeof(client_addr);
// 接收客户端消息
ssize_t len = recvfrom(server_fd, buffer, BUFF_LEN, 0, (struct sockaddr *)&client_addr, &client_len);
if (len < 0) {
perror("recvfrom error");
continue;
}
buffer[len] = '\0';
printf("Received message: %s\n", buffer);
// 回复客户端消息
const char *response = "Received";
sendto(server_fd, response, strlen(response), 0, (struct sockaddr *)&client_addr, client_len);
}
close(server_fd);
return 0;
}
这段代码创建了一个UDP服务器,监听在端口8080上的消息。当服务器接收到消息时,它会打印出来,并向发送消息的客户端回复一个"Received"字符串。这个简单的UDP服务器提供了一个基本的框架,可以根据实际需求进行扩展和修改。
评论已关闭