-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_main.cpp
71 lines (63 loc) · 2.02 KB
/
server_main.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
#include <cstring>
#include <iostream>
#include <string>
#include <thread>
#include "tcp_server.hpp"
#include "tcp_socket.hpp"
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cout << "usage: " << argv[0] << " <port>\n";
return 1;
}
try
{
tcp_server server;
uint16_t port = std::stoi(argv[1]);
server.set_callback(
[](tcp_socket&& s)
{
// when we get a connection, spawn a new thread to handle
// the connection. Be aware, the thread is not being cleaned up!!
new std::thread(
[s = std::move(s)]() mutable
{
std::cout << "starting client: " << std::this_thread::get_id() << "\n";
while (true)
{
auto received = s.read();
if (strncmp(received.data(), "quit", 4) == 0)
{
std::cout << "client shutdown: " << std::this_thread::get_id() << "\n";
return;
}
if (!s.write("you wrote: " + received))
{
std::cout << "connection closed: " << std::this_thread::get_id() << "\n";
return;
}
}
});
});
server.start(port);
std::cout << "started server on port: " << port << "...\n";
// check for local termination of the server
std::string repl;
while (true)
{
std::getline(std::cin, repl);
if (repl == "quit")
break;
}
std::cout << "server shutting down...";
server.stop();
std::cout << "done!\n";
}
catch (std::exception& e)
{
std::cerr << e.what() << "\n";
return 1;
}
return 0;
}