forked from yedf2/handy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.cc
62 lines (57 loc) · 2.1 KB
/
chat.cc
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
#include <handy/handy.h>
#include <map>
using namespace std;
using namespace handy;
int main(int argc, const char* argv[]) {
setloglevel("TRACE");
map<intptr_t, TcpConnPtr> users; //生命周期比连接更长,必须放在Base前
EventBase base;
Signal::signal(SIGINT, [&]{ base.exit(); });
int userid = 1;
TcpServerPtr chat = TcpServer::startServer(&base, "", 2099);
exitif(chat == NULL, "start tcpserver failed");
chat->onConnCreate([&]{
TcpConnPtr con(new TcpConn);
con->onState([&](const TcpConnPtr& con) {
if (con->getState() == TcpConn::Connected) {
con->context<int>() = userid;
const char* welcome = "<id> <msg>: send msg to <id>\n<msg>: send msg to all\n\nhello %d";
con->sendMsg(util::format(welcome, userid));
users[userid] = con;
userid ++;
} else if (con->getState() == TcpConn::Closed) {
users.erase(con->context<int>());
}
});
con->onMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg){
if (msg.size() == 0) { //忽略空消息
return;
}
int cid = con->context<int>();
char* p = (char*)msg.data();
intptr_t id = strtol(p, &p, 10);
p += *p == ' '; //忽略一个空格
string resp = util::format("%ld# %.*s", cid, msg.end()-p, p);
int sended = 0;
if (id == 0) { //发给其他所有用户
for(auto& pc: users) {
if (pc.first != cid) {
sended ++;
pc.second->sendMsg(resp);
}
}
} else { //发给特定用户
auto p1 = users.find(id);
if (p1 != users.end()) {
sended ++;
p1->second->sendMsg(resp);
}
}
con->sendMsg(util::format("#sended to %d users", sended));
});
return con;
});
base.loop();
info("program exited");
return 0;
}