epoll相对于poll和select这两个多路复用的I/O模型更加的高效。epoll的函数很简单,麻烦的地方在于水平触发和边沿触发。

用张图来说明下

ET(边沿)只是在状态反转时触发,比如从不可读到可读。而LT(水平)就是如果可读,就会一直触发。所以在使用ET的时候要做一些额外的处理,比如可读的,一直把缓冲区读完,进入不可读状态,下次来数据才会触发。

下面贴出代码,只是一个简单的练习的例子
socketheads.h

 
 
 
 
 

C++

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef SOCKETHEADS_H
#define SOCKETHEADS_H
 
 
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
#endif //SOCKETHEADS_H

zepoll.h

 
 
 
 
 

C++

 
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
#ifndef EPOLL_H
#define EPOLL_H
 
#include <sys/epoll.h>
#include <unistd.h>
 
 
/**
* @brief The Epoll class 对epoll的封装
*/
class Epoll
{
public:
    /**
     *
     */
    enum EPOLL_OP {ADD = EPOLL_CTL_ADD, MOD = EPOLL_CTL_MOD, DEL = EPOLL_CTL_DEL};
    /**
     * 最大的连接数和最大的回传事件数
     */
    Epoll(int _max = 30, int maxevents = 20);
    ~Epoll();
    int create();
    int add(int fd, epoll_event *event);
    int mod(int fd, epoll_event *event);
    int del(int fd, epoll_event *event);
    void setTimeout(int timeout);
    void setMaxEvents(int maxevents);
    int wait();
    const epoll_event* events() const;
    const epoll_event& operator[](int index)
    {
        return backEvents[index];
    }
private:
    bool isValid() const;
    int max;
    int epoll_fd;
    int epoll_timeout;
    int epoll_maxevents;
    epoll_event *backEvents;
};
 
#endif //EPOLL_H

zepoll.cpp

 
 
 
 
 

C++

 
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
#include "zepoll.h"
 
Epoll::Epoll(int _max, int maxevents):max(_max),
    epoll_fd(-1),
    epoll_timeout(0),
    epoll_maxevents(maxevents),
    backEvents(0)
{
 
}
 
Epoll::~Epoll()
{
    if (isValid()) {
        close(epoll_fd);
    }
    delete[] backEvents;
}
 
 
inline
bool Epoll::isValid() const
{
    return epoll_fd > 0;
}
 
inline
void Epoll::setTimeout(int timeout)
{
    epoll_timeout = timeout;
}
 
inline
void Epoll::setMaxEvents(int maxevents)
{
    epoll_maxevents = maxevents;
}
 
inline
const epoll_event* Epoll::events() const
{
    return backEvents;
}
 
 
 
int Epoll::create()
{
    epoll_fd = ::epoll_create(max);
    if (isValid()) {
        backEvents = new epoll_event[epoll_maxevents];
    }
    return epoll_fd;
}
 
int Epoll::add(int fd, epoll_event *event)
{
    if (isValid()) {
        return ::epoll_ctl(epoll_fd, ADD, fd, event);
    }
    return -1;
 
}
 
int Epoll::mod(int fd, epoll_event *event)
{
    if (isValid()) {
        return ::epoll_ctl(epoll_fd, MOD, fd, event);
    }
    return -1;
 
}
 
int Epoll::del(int fd, epoll_event *event)
{
    if (isValid()) {
        return ::epoll_ctl(epoll_fd, DEL, fd, event);
    }
    return -1;
}
 
int Epoll::wait()
{
    if (isValid()) {
        return ::epoll_wait(epoll_fd, backEvents, epoll_maxevents, epoll_timeout);
    }
    return -1;
}

task.h

 
 
 
 
 

C++

 
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
/********************************************************************
* author 周翔
* e-mail 604487178@qq.com
* blog http://blog.csdn.net/zhx6044
**********************************************************************/
 
#ifndef TASK_H
#define TASK_H
 
#include <string>
#include <socketheads.h>
 
/**
* @brief The Task class 任务类
*/
class Task
{
public:
    typedef enum {CONNECT = 0, DISCONNECT, TALKING} TASKFLAG;
    Task(const std::string &message, TASKFLAG flag = TALKING);
    const std::string& getMessage() const;
    TASKFLAG getFlag() const;
    void setIP(in_addr _ip);
    int getS_fd() const;
 
    void setS_fd(int _fd);
 
 
    std::string getData() const;
 
 
private:
    std::string m_message;
    TASKFLAG m_flag;
    in_addr ip;
    int s_fd;
};
 
#endif // TASK_H

task.cpp

 
 
 
 
 

C++

 
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
/********************************************************************
* author 周翔
* e-mail 604487178@qq.com
* blog http://blog.csdn.net/zhx6044
**********************************************************************/
 
#include "task.h"
 
Task::Task(const std::string &message, TASKFLAG flag):
    m_message(message),
    m_flag(flag)
{
}
 
 
const std::string& Task::getMessage() const
{
    return m_message;
}
 
Task::TASKFLAG Task::getFlag() const
{
    return m_flag;
}
 
void Task::setIP(in_addr _ip)
{
    ip = _ip;
}
 
int Task::getS_fd() const
{
    return s_fd;
}
 
void Task::setS_fd(int _fd)
{
    s_fd = _fd;
}
 
std::string Task::getData() const
{
    std::string re;
    if (m_flag == CONNECT) {
        re = ::inet_ntoa(ip) + std::string("----->") + "CONNECT!    " + m_message;
    } else {
        if (m_flag == DISCONNECT) {
            re = ::inet_ntoa(ip) + std::string("----->") + "DISCONNECT   " + m_message;;
        } else {
            re = ::inet_ntoa(ip) + std::string("----->Talk:") + m_message;
        }
    }
    return re;
}

epoll_server.h

 
 
 
 
 

C++

 
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
#ifndef EPOLL_SERVER_H
#define EPOLL_SERVER_H
 
#include <map>
#include <list>
 
#include "zepoll.h"
#include "socketheads.h"
#include "task.h"
 
 
typedef std::pair<int, in_addr> FDtoIP;
 
/**
* @brief The Epoll_server class 服务器
*/
class Epoll_server
{
public:
    Epoll_server(int port);
    ~Epoll_server();
    int bind();
    int listen();
    void poweroff();
    bool states() const;
private:
    enum  {BLOCKLOG = 5};
 
    bool isValid() const;
 
    int acceptSocketEpoll();
    int readSocketEpoll(const epoll_event &ev);
    int writeSocketEpoll(const epoll_event &ev);
 
    void doTask(const Task &t);
 
    int _port;
    int server_socket_fd;
    Epoll *_epoll;
    sockaddr_in server_addr;
    sockaddr_in client_addr;
    epoll_event m_event;
    bool on;
    static int setNonblocking(int socket_fd);
    std::list<FDtoIP> fd_IP;
};
 
#endif //EPOLL_SERVER_H

epoll_server.cpp

 
 
 
 
 

C++

 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#include "epoll_server.h"
 
#include <iostream>
 
 
//static char welcom[] = "welcom to my epoll_server";
//static char sorry[] = "Sorry! This is a simple demo,so not any function!";
//static char buf[BUFSIZ];
 
 
Epoll_server::Epoll_server(int port):_port(port),
    server_socket_fd(-1),
    _epoll(0),
    on(true)
{
 
 
}
 
 
Epoll_server::~Epoll_server()
{
    if (isValid()) {
        ::close(server_socket_fd);
    }
    delete _epoll;
 
}
 
 
inline
bool Epoll_server::isValid() const
{
    return server_socket_fd > 0;
}
 
 
inline
void Epoll_server::poweroff()
{
    on = false;
}
 
 
 
inline
bool Epoll_server::states() const
{
    return on;
}
 
 
 
int Epoll_server::setNonblocking(int socket_fd)
{
    int opts;
    opts = fcntl(socket_fd, F_GETFL);
    if (opts < 0) {
        return -1;
    } else
    {
        opts = opts | O_NONBLOCK;
        if (fcntl(socket_fd, F_SETFL, opts) < 0) {
 
            return -1;
        }
    }
    return 0;
}
 
 
void Epoll_server::doTask(const Task &t)
{
    std::list<FDtoIP>::iterator ite = fd_IP.begin();
    std::list<FDtoIP>::iterator ite1 = fd_IP.end();
    for (;ite != fd_IP.end();++ite) {
        if ((*ite).first != t.getS_fd()) {
            memset(&m_event, '\0', sizeof(m_event));
            m_event.events = EPOLLOUT | EPOLLET;
            Task *c = new Task(t);
            c->setS_fd((*ite).first);
            m_event.data.ptr = static_cast<void*>(c);
            _epoll->mod((*ite).first, &m_event);
        } else {
            ite1 = ite;
        }
    }
    if (t.getFlag() == Task::DISCONNECT) {
        if (ite1 != fd_IP.end()) {
            fd_IP.erase(ite1);
        }
    }
}
 
/**
* @brief Epoll_server::acceptSocketEpoll 有用户接入
* @return
*/
int Epoll_server::acceptSocketEpoll()
{
    socklen_t len = sizeof(struct sockaddr_in);
    int connect_fd;
    while ((connect_fd = ::accept(server_socket_fd,
                                  (struct sockaddr*)(&client_addr), &len)) > 0) {
        if (setNonblocking(connect_fd) < 0) {
            ::close(connect_fd);
            continue;
        }
        m_event.data.fd = connect_fd;
        m_event.events = EPOLLIN | EPOLLET;
        if (_epoll->add(connect_fd, &m_event) < 0) {
            ::close(connect_fd);
            continue;
        } else {
 
            fd_IP.push_back(FDtoIP(connect_fd, client_addr.sin_addr));
            Task t("come in", Task::CONNECT);
            t.setIP(client_addr.sin_addr);
            t.setS_fd(connect_fd);
            doTask(t);
        }
    }
 
    if (connect_fd == -1 && errno != EAGAIN && errno != ECONNABORTED
            && errno != EPROTO && errno !=EINTR) {
        return -1;
    }
    return 0;
}
 
 
int Epoll_server::readSocketEpoll(const epoll_event &ev)
{
    int n = 0;
    int nread = 0;
    char buf[BUFSIZ]={'\0'};
    while ((nread = ::read(ev.data.fd, buf + n, BUFSIZ-1)) > 0) {
        n += nread;
    }
    if (nread == -1 && errno != EAGAIN) {
        return -1;
    }
 
    std::list<FDtoIP>::iterator ite = fd_IP.begin();
    for (;ite != fd_IP.end();++ite) {
        if ((*ite).first == ev.data.fd) {
            break;
        }
    }
 
    if (nread == 0) {
        strcpy(buf, " disconet  left ");
        Task t(buf,Task::DISCONNECT);
        t.setIP(client_addr.sin_addr);
        t.setS_fd((*ite).first);
        doTask(t);
    } else {
        Task t(buf,Task::TALKING);
        t.setIP(client_addr.sin_addr);
        t.setS_fd((*ite).first);
        doTask(t);
    }
 
    //    Task *t = new Task(buf,Task::DISCONNECT);
    //    t->setIP((*ite).second);
    //    t->setS_fd((*ite).first);
 
 
 
 
    // m_event.data.fd = ev.data.fd;
    // m_event.events = ev.events;
    return 0;//_epoll->mod(m_event.data.fd, &m_event);
}
 
 
int Epoll_server::writeSocketEpoll(const epoll_event &ev)
{
    Task *t = static_cast<Task*>(ev.data.ptr);
    const char* buf = t->getData().data();
    int nwrite = 0, data_size = strlen(buf);
    int fd = t->getS_fd();
    int n = data_size;
    delete t;
    while (n > 0) {
        nwrite = ::write(fd, buf + data_size - n, n);
        if (nwrite < 0) {
            if (nwrite == -1 && errno != EAGAIN) {
                return -1;
            }
            break;
        }
        n -= nwrite;
    }
 
    memset(&m_event, '\0', sizeof(m_event));
    // m_event.events &= ~EPOLLOUT;
    m_event.events = EPOLLIN | EPOLLET;
    m_event.data.fd = fd;
    if (_epoll->mod(fd, &m_event) < 0) {
        ::close(m_event.data.fd);
        return -1;
    }
    return 0;
}
 
/**
* @brief Epoll_server::bind
* @return
*/
int Epoll_server::bind()
{
    server_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket_fd < 0) {
        return -1;
    }
 
    setNonblocking(server_socket_fd);
 
    _epoll = new Epoll();
    if (_epoll->create() < 0) {
        return -1;
    }
    memset(&m_event, '\0', sizeof(m_event));
    m_event.data.fd = server_socket_fd;
    m_event.events = EPOLLIN | EPOLLET;
    _epoll->add(server_socket_fd, &m_event);
 
    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(_port);
 
    return ::bind(server_socket_fd, (struct sockaddr*)(&server_addr), sizeof(struct sockaddr));
 
}
 
 
int Epoll_server::listen()
{
    if (isValid()) {
        if (::listen(server_socket_fd, BLOCKLOG) < 0) {
            return -1;
        } else {
            int num;
            while (on) {
                num = _epoll->wait();
                for (int i = 0;i < num;++i) {
                    /**
                     * 接受连接的连接,把她加入到epoll中
                     */
                    if ((*_epoll)[i].data.fd == server_socket_fd) {
                        if (acceptSocketEpoll() < 0) {
                            break;
                        }
                        continue;
 
                    }
                    /**
                     * EPOLLIN event
                     */
                    if ((*_epoll)[i].events & EPOLLIN) {
                        if (readSocketEpoll((*_epoll)[i]) < 0) {
                            break;
                        }
                        continue;
 
 
                    }
 
                    /**
                     * EPOLLOUT event
                     */
                    if ((*_epoll)[i].events & EPOLLOUT) {
                        if (writeSocketEpoll((*_epoll)[i]) < 0) {
                            break;
                        }
 
                    }
                }
            }
        }
    }
    return -1;
}

main.cpp

 
 
 
 
 

C++

 
1
2
3
4
5
6
7
8
9
10
11
12
#include "epoll_server.h"
#include <iostream>
 
int main(int /*argc*/, char const **/*argv[]*/)
{
    std::cout << "server" << std::endl;
    Epoll_server s(18090);
    if (s.bind() < 0) {
        return -1;
    }
    return s.listen();
}

客户端用qt简单的写了一个

客户端服务端代码:epoll_chatroom.zip

http://love.junzimu.com/archives/2660

基于epoll的聊天室程序的更多相关文章

  1. 基于swoole搭建聊天室程序

    1. 创建websocket服务器 swoole从1.7.9版本开始, 内置了websocket服务器功能,我们只需几行简单的PHP代码,就可以创建出一个异步非阻塞多进程的WebSocket服务器. ...

  2. 基于select的python聊天室程序

    python网络编程具体参考<python select网络编程详细介绍>. 在python中,select函数是一个对底层操作系统的直接访问的接口.它用来监控sockets.files和 ...

  3. 使用Beetle简单构建聊天室程序

    之前已经讲解了Beetle简单地构建网络通讯程序,那程序紧紧是讲述了如何发送和接收数据:这一章将更深入的使用Beetle的功能,主要包括消息制定,协议分析包括消息接管处理等常用的功能.为了更好的描述所 ...

  4. Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G

    code&monkey   Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...

  5. ASP.NET 使用application和session对象写的简单聊天室程序

    ASP.Net中有两个重要的对象,一个是application对象,一个是session对象. Application:记录应用程序参数的对象,该对象用于共享应用程序级信息. Session:记录浏览 ...

  6. 高级IO复用应用:聊天室程序

    简单的聊天室程序:客户端从标准输入输入数据后发送给服务端,服务端将用户发送来的数据转发给其它用户.这里采用IO复用poll技术.客户端采用了splice零拷贝.服务端采用了空间换时间(分配超大的用户数 ...

  7. 基于WebSocket实现聊天室(Node)

    基于WebSocket实现聊天室(Node) WebSocket是基于TCP的长连接通信协议,服务端可以主动向前端传递数据,相比比AJAX轮询服务器,WebSocket采用监听的方式,减轻了服务器压力 ...

  8. 用c写一个小的聊天室程序

    1.聊天室程序——客户端 客户端我也用了select进行I/O复用,同时监控是否有来自socket的消息和标准输入,近似可以完成对键盘的中断使用. 其中select的监控里,STDOUT和STDIN是 ...

  9. Erlang 聊天室程序

    Erlang 聊天室程序( 一) Erlang 聊天室程序(二) 客户端的退出 Erlang 聊天室程序(三) 数据交换格式---json的decode Erlang 聊天室程序(四) 数据交换格式- ...

随机推荐

  1. Eclipse vim插件安装使用

    在eclipse移动关闭位置感觉非常不爽,经常要用到方向键和鼠标,导致经常要移来移去.果断受不了了,去网上搜了下发现eclipse有许多vim插件可以使用.有一个大家都比较推荐的是 vrapper   ...

  2. HDU1841——KMP算法

    这个题..需要对KMP的模板理解的比较透彻,以前我也只是会套模板..后来才知道..之会套模板是不行的..如果不能把握模板的每一个细节`,至少能搞清楚模板的每一个模块大体是什么意思.. 题意是给出两个串 ...

  3. 【Python脚本】Eclipse IDE扩展PyDev插件安装

    作为一名Python的初学者,其实不用太在意IDE了,我觉得开始的时候用用自带的 IDLE 也挺好的. 还有 DreamPie 也挺好的.都是一些轻量级的IDE. 因为我正好安装有Eclipse,平时 ...

  4. ListView之ArrayAdapter

    ArrayAdapter 普通的显示listView子项,安卓的内置对象 使用方法: /* ListView :列表 通常有两个职责: a.将数据填充到布局 b.处理点击事件 一个ListView创建 ...

  5. 简易的C/S系统(实现两个数的和)

    //Client:#include <string.h> #include <sys/socket.h> #include <stdio.h> #include & ...

  6. C++中,访问字符串的三种方法

    1.用字符数组存放一个字符串 程序1:定义一个字符数组并初始化,然后输出其中的字符串. #include<iostream> using namespace std; int main() ...

  7. 几个检查当前运行的LINUX是在VM还是在实体机中的方法

    昨天提到了VM中的逃逸问题,要想逃逸,首先要检测当前操作系统是否为VM,下面提供几个LINUX下的检查方法: 第一,首推facter virtual ,权限为普通用户,约定,普通用户命令提示符用$表示 ...

  8. BASE64Encoder问题类

    于myeclipse于BASE64Encoder提示类不出现 对当前右击project-->Build Path--->Configure Build Path--->Java Bu ...

  9. Java中的编码格式

    Java中的编码 gbk编码 中文占用2个字节,英文占1个字节; utf-8编码 中文占用3个字节.,英文占用1个字节; Java是双字节编码 (utf-16be) utf -16be 中文占2个字节 ...

  10. SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问的解决方案

    今天写了一个excel表的导入功能,结果在excel表中的内容导入到页面时报错:SQL  Server 阻止了对组件 'Ad Hoc Distributed Queries' 的  STATEMENT ...