-
Notifications
You must be signed in to change notification settings - Fork 0
/
simepoll.cpp
124 lines (121 loc) · 4.34 KB
/
simepoll.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include "Sock.hpp"
#define SIZE 128
#define NUM 64
void Usage(std::string proc)
{
std::cout << "Usage: ./" << proc << " port" << std::endl;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
Usage(argv[0]);
exit(2);
}
// 1. 建立tcp监听套接字
uint16_t port = atoi(argv[1]);
int listen_sock = Sock::Socket();
Sock::Bind(listen_sock, port);
Sock::Listen(listen_sock);
// 2. 创建epoll模型
int epfd = epoll_create(SIZE);
// 3. 添加listen_sock和他所关心的事件到内核
struct epoll_event ev;
ev.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, listen_sock, &ev);
// 4. 事件循环
volatile bool quit = false;
struct epoll_event revs[NUM];
while (!quit)
{
int timeout = 1000;
int n = epoll_wait(epfd, revs, NUM, timeout);
switch (n)
{
case 0:
std::cout << "timeout..." << std::endl;
break;
case -1:
std::cout << "epoll error..." << std::endl;
break;
default:
std::cout << "有事件就绪了..." << std::endl;
// 5. 处理就绪事件
for (int i = 0; i < n; ++i)
{
// 暂时方案
int sock = revs[i].data.fd;
std::cout << "文件描述符" << sock << "上有事件就绪..." << std::endl;
if (revs[i].events & EPOLLIN)
{
std::cout << "文件描述符" << sock << "上有读事件就绪..." << std::endl;
if (sock == listen_sock)
{
// 5.1 处理新链接到来
std::cout << "listen_sock: " << listen_sock << "上有读事件就绪..." << std::endl;
int new_sock = Sock::Accept(listen_sock);
if (new_sock >= 0)
{
// 把新链接添加到epoll中
struct epoll_event curev;
curev.events = EPOLLIN;
curev.data.fd = new_sock;
epoll_ctl(epfd, EPOLL_CTL_ADD, new_sock, &curev);
}
}
else
{
// 5.2 处理普通sock的读事件
std::cout << "sock: " << sock << "上有内容待续..." << std::endl;
char buffer[1024];
int s = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (s > 0)
{
// 读到内容了
buffer[s - 1] = '\0';
std::cout << "client[" << sock << "] say $ " << buffer << std::endl;
// 读完后设置写响应
struct epoll_event curev;
curev.events = EPOLLOUT;
ev.data.fd = sock;
epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &curev);
}
else if (s == 0)
{
// 客户端关闭链接
close(sock);
epoll_ctl(epfd, EPOLL_CTL_DEL, sock, nullptr);
std::cout << "client[" << sock << "] exit..." << std::endl;
}
else
{
// 读取错误
close(sock);
epoll_event curcv;
curcv.events = EPOLLIN;
curcv.data.fd = sock;
epoll_ctl(epfd, EPOLL_CTL_DEL, sock, &curcv);
std::cout << "client[" << sock << "] read error..." << std::endl;
}
}
}
else if (revs[i].events & EPOLLOUT)
{
// 处理写事件
}
else
{
// 其他
}
}
break;
}
}
close(epfd);
return 0;
}