forked from andreimaximov/uthread
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.cpp
More file actions
171 lines (139 loc) · 4.04 KB
/
Copy pathchat.cpp
File metadata and controls
171 lines (139 loc) · 4.04 KB
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
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <uthread/uthread.hpp>
DEFINE_uint32(port, 8000, "The TCP port number to run the server on.");
struct User {
/** The name of this user. */
std::string name;
/** The sequence number of the next message we should send this user. */
size_t seq;
/** The TCP connection for this user. */
std::shared_ptr<uthread::TcpStream> stream;
User() {
stream = std::make_shared<uthread::TcpStream>();
}
};
struct Room {
/** The message log which we do NOT truncate fo simplicity. */
std::vector<std::string> log;
/** The name allocator for new connections. */
uthread::MpmcQueue<std::string> names;
Room() {
names.push("Anonymous Iguana");
names.push("Anonymous Turtle");
names.push("Anonymous Bear");
names.push("Anonymous Whale");
names.push("Anonymous Shark");
names.push("Anonymous Elephant");
names.push("Anonymous Wolf");
names.push("Anonymous Moose");
}
};
struct Framer {
std::string buf;
/** Appends a char sequence to the framer. */
void append(const char *buf_, size_t buf_size) {
buf.append(buf_, buf_size);
}
/** Checks if the framer has a line. */
bool has() {
auto p = buf.find('\n');
return (p != std::string::npos);
}
/** Pops a line from the framer. */
std::string pop() {
auto p = buf.find('\n');
CHECK_NE(p, std::string::npos);
auto s = buf.substr(0, p);
buf.erase(0, p + 1);
return s;
}
};
/** Our chat room. */
static Room gRoom;
static void post(const User &user, std::string message) {
static const std::string kWhitespace = " \t\r\n";
// http://www.toptip.ca/2010/03/trim-leading-or-trailing-white-spaces.html
auto p = message.find_first_not_of(kWhitespace);
message.erase(0, p);
p = message.find_last_not_of(kWhitespace);
if (p != std::string::npos)
message.erase(p + 1);
if (message.empty())
return;
gRoom.log.push_back(user.name + ": " + message + "\n");
}
static void worker(User user) {
post(user, "Connected");
auto ok = true;
// Send the log to this user.
auto send = uthread::Executor::get()->add([&]() {
while (ok) {
if (user.seq < gRoom.log.size()) {
const std::string &mess = gRoom.log[user.seq];
if (user.stream->send(mess.c_str(), mess.size()) == 0) {
user.seq++;
} else {
ok = false;
}
} else {
uthread::Executor::get()->yield();
}
}
});
// Append messages from this user to the log.
auto recv = uthread::Executor::get()->add([&]() {
Framer framer;
char buf[1024];
while (ok) {
auto r = user.stream->recv(buf, sizeof(buf));
if (r >= 0) {
framer.append(buf, r);
} else {
ok = false;
}
while (framer.has()) {
post(user, framer.pop());
}
}
});
send.join();
recv.join();
// Send a notification that the user has disconnected and reuse the name.
post(user, "Disconnected");
gRoom.names.push(user.name);
}
static void run() {
uthread::TcpListener listener;
CHECK_NE(listener.bind("127.0.0.1", FLAGS_port), -1)
<< "Error binding listener!";
while (true) {
// Wait for a name to become available. This is a primitive way of
// limiting the number of users in our chat room.
User user;
gRoom.names.pop(user.name);
// A name has been allocated, so now we just wait for a connection.
if (listener.accept(*user.stream) != 0)
LOG(FATAL) << "Error accepting connection!";
user.seq = gRoom.log.size();
uthread::Executor::get()->add([user]() { worker(user); });
}
}
int main(int argc, char *argv[]) {
gflags::SetUsageMessage("A TCP echo server");
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
std::cout << "Running a chat server; Use 'ncat 127.0.0.1 "
<< FLAGS_port
<< "' to send messages."
<< std::endl;
uthread::Executor exe;
uthread::Io io(&exe);
exe.add(run);
exe.run();
return 0;
}