-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
55 lines (45 loc) · 1.06 KB
/
server.cpp
File metadata and controls
55 lines (45 loc) · 1.06 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
#include "pch.hpp"
#include "session.hpp"
#include "server.hpp"
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: server <port>\n";
return 1;
}
try {
asio::io_context io;
Server serv(io, atoi(argv[1]));
io.run();
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
Server::Server(asio::io_context& io, int port)
: io_(io),
acceptor_(io, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
void Server::broadcast(const std::string& msg, std::shared_ptr<Session> sender) {
for (auto& client : clients) {
if (client != sender) {
client->deliver(msg);
}
}
}
void Server::leave(std::shared_ptr<Session> session) {
clients.erase(session);
}
void Server::start_accept() {
auto new_connection = Session::create(io_, *this);
acceptor_.async_accept(new_connection->socket(),
[this, new_connection](std::error_code ec) {
if (!ec) {
clients.insert(new_connection);
new_connection->start();
std::cout << "Someone connected\n";
}
start_accept(); // accept next client
});
}