设计Linux环境下的UDP socket通信程序,实现服务器端和客户端的通信并说明运行后怎么进行通信
时间: 2023-05-30 14:04:19 浏览: 125
以下是Linux环境下的UDP socket通信程序的示例:
服务器端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8888
#define MAX_BUFFER_SIZE 1024
int main() {
// 创建UDP socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// 将socket绑定到服务器地址
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 接收客户端消息并回复
char buffer[MAX_BUFFER_SIZE];
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
while (1) {
int n = recvfrom(sockfd, buffer, MAX_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&cliaddr, &len);
buffer[n] = '\0';
printf("Received message from client: %s\n", buffer);
sendto(sockfd, "Hello from server!", strlen("Hello from server!"), MSG_CONFIRM, (const struct sockaddr *)&cliaddr, len);
}
// 关闭socket
close(sockfd);
return 0;
}
```
客户端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
#define MAX_BUFFER_SIZE 1024
int main() {
// 创建UDP socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
// 发送消息给服务器
char buffer[MAX_BUFFER_SIZE];
printf("Enter message to send to server: ");
fgets(buffer, MAX_BUFFER_SIZE, stdin);
sendto(sockfd, buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&servaddr, sizeof(servaddr));
printf("Message sent to server.\n");
// 接收服务器回复
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
int n = recvfrom(sockfd, buffer, MAX_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&cliaddr, &len);
buffer[n] = '\0';
printf("Received message from server: %s\n", buffer);
// 关闭socket
close(sockfd);
return 0;
}
```
运行方法:
1. 打开终端,编译服务器端代码:`gcc server.c -o server`
2. 打开另一个终端,编译客户端代码:`gcc client.c -o client`
3. 在第一个终端中运行服务器端程序:`./server`
4. 在第二个终端中运行客户端程序:`./client`
5. 在客户端终端中输入要发送的消息,按回车键发送
6. 在服务器端终端中可以看到接收到的消息,并回复"Hello from server!"
7. 在客户端终端中可以看到收到的回复消息
以上程序实现了基本的UDP socket通信,客户端将消息发送给服务器,服务器接收到消息后回复。可以根据实际需求修改代码来实现更复杂的功能。
阅读全文