基于UDP传输的C语言聊天小程序
下面是一个简单的UDP聊天程序的示例代码,实现了客户端和服务器端的基本功能。
服务器端 (server.c
):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
#define SERVER_PORT 8888
int main() {
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len;
int sock_fd;
char buf[BUF_SIZE];
int i, res;
// 创建socket
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
// 定义服务器地址
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到地址
bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
printf("Server is running on port %d, waiting for messages...\n", SERVER_PORT);
while (1) {
addr_len = sizeof(client_addr);
// 接收数据
res = recvfrom(sock_fd, buf, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len);
if (res == -1) {
perror("recvfrom error");
continue;
}
buf[res] = '\0';
printf("Received message: %s\n", buf);
// 发送数据回客户端
strcat(buf, " (from server)");
res = sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&client_addr, addr_len);
if (res == -1) {
perror("sendto error");
}
}
close(sock_fd);
return 0;
}
客户端 (client.c
):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
#define SERVER_PORT 8888
#define SERVER_IP "127.0.0.1"
int main() {
struct sockaddr_in server_addr;
int sock_fd;
char buf[BUF_SIZE];
int res;
// 创建socket
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
// 定义服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(SERVER_PORT);
printf("Chat client is running, enter messages and hit enter to send.\n");
while (fgets(buf, BUF_SIZE, stdin) != NULL) {
// 发送数据到服务器
res = sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (res == -1) {
perror("sendto error");
continue;
}
// 接收来
评论已关闭