C语言使用udp进行进程间全双工通信代码
时间: 2023-06-11 21:09:27 浏览: 102
以下是使用UDP进行进程间全双工通信的示例代码:
// Server端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int server_fd, client_fd, recv_len;
struct sockaddr_in server_addr, client_addr;
char buffer[MAX_BUFFER_SIZE] = {0};
socklen_t addr_len = sizeof(client_addr);
// 创建UDP套接字
if ((server_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 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 = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定套接字
if (bind(server_fd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
while (1) {
// 从客户端接收数据
recv_len = recvfrom(server_fd, buffer, MAX_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&client_addr, &addr_len);
buffer[recv_len] = '\0';
printf("Client: %s\n", buffer);
// 向客户端发送数据
printf("Server: ");
fgets(buffer, MAX_BUFFER_SIZE, stdin);
sendto(server_fd, buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&client_addr, addr_len);
}
close(server_fd);
return 0;
}
// Client端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int client_fd, recv_len;
struct sockaddr_in server_addr;
char buffer[MAX_BUFFER_SIZE] = {0};
// 创建UDP套接字
if ((client_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {
perror("inet_pton failed");
exit(EXIT_FAILURE);
}
while (1) {
// 向服务器发送数据
printf("Client: ");
fgets(buffer, MAX_BUFFER_SIZE, stdin);
sendto(client_fd, buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&server_addr, sizeof(server_addr));
// 从服务器接收数据
recv_len = recvfrom(client_fd, buffer, MAX_BUFFER_SIZE, MSG_WAITALL, NULL, NULL);
buffer[recv_len] = '\0';
printf("Server: %s\n", buffer);
}
close(client_fd);
return 0;
}
阅读全文