写点什么

linux 环境下用 c 语言实现 reactor 网络模型的代码案例

作者:linux大本营
  • 2023-04-21
    湖南
  • 本文字数:1697 字

    阅读完需:约 6 分钟

下面是一个简单的例子,演示在 Linux 环境下使用 C 语言编写 Reactor 网络模型的代码。


#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <sys/epoll.h>
#define PORT 8888 // 定义服务器端口号#define MAX_EVENTS 10#define BUFFER_SIZE 1024
int main() { struct epoll_event event, events[MAX_EVENTS]; int listen_fd, new_fd, epoll_fd, num_events, i; struct sockaddr_in server_addr, client_addr; socklen_t sin_size = sizeof(client_addr); char buffer[BUFFER_SIZE];
// 创建服务器套接字 if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket failed"); exit(EXIT_FAILURE); } // 设置服务器地址和端口号并绑定 server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero)); if (bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind failed"); exit(EXIT_FAILURE); } // 监听客户端连接 if (listen(listen_fd, 10) == -1) { perror("listen failed"); exit(EXIT_FAILURE); }
// 创建 epoll 实例并将服务器 socket 注册到 epoll 事件中 if ((epoll_fd = epoll_create(MAX_EVENTS)) == -1) { perror("epoll_create failed"); exit(EXIT_FAILURE); } event.events = EPOLLIN; event.data.fd = listen_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &event) == -1) { perror("epoll_ctl failed"); exit(EXIT_FAILURE); } // 循环接收客户端连接并读写数据 while (1) { num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); for (i = 0; i < num_events; i++) { if (events[i].data.fd == listen_fd) { // 有新的客户端连接 new_fd = accept(listen_fd, (struct sockaddr *)&client_addr, &sin_size); printf("New client connected: %s\n", inet_ntoa(client_addr.sin_addr)); event.events = EPOLLIN; event.data.fd = new_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, new_fd, &event) == -1) { perror("epoll_ctl failed"); exit(EXIT_FAILURE); } } else { // 有客户端发送消息 if ((num_events = read(events[i].data.fd, buffer, BUFFER_SIZE)) <= 0) { close(events[i].data.fd); if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &event) == -1) { perror("epoll_ctl failed"); exit(EXIT_FAILURE); } printf("Client disconnected.\n"); } else { // 处理客户端的请求 buffer[num_events] = '\0'; printf("Received message: %s\n", buffer); if (send(events[i].data.fd, buffer, strlen(buffer), 0) == -1) { perror("send failed"); exit(EXIT_FAILURE); } } } } }
return 0;}
复制代码


相关技术视频教程:c/c++ linux服务器开发/后台架构师免费学习地址

c/c++后端技术交流群:812855908

用户头像

还未添加个人签名 2020-11-26 加入

C/C++linux服务器开发群 812855908

评论

发布
暂无评论
linux环境下用c语言实现reactor网络模型的代码案例_Linux_linux大本营_InfoQ写作社区