-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
55 lines (48 loc) · 1 KB
/
Server.cpp
File metadata and controls
55 lines (48 loc) · 1 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 "Server.h"
#include "warning.h"
#include "Socket.h"
#include <unistd.h>
#include <stdexcept>
using namespace std::string_literals;
Server& Server::listen(int port)
{
Socket listener;
listener.bind(port);
listener.listen();
// Wait for connections
while(true)
{
Socket connection(listener.accept());
if(!connection.isValid())
{
warning("Failed to accept incoming connection");
continue;
}
const auto pid = fork();
if(pid == 0)
{
// Newborn child acts as response server to client
// then kills itself when the client hangs up
listener.close();
while(true)
{
try
{
auto message_from_client = connection.receive();
const auto message_to_client = this->handler(std::move(message_from_client));
connection.send(message_to_client);
}
catch(const Socket::PeerDisconnect&)
{
break;
}
catch(const std::exception& e)
{
warning("Exception in server event loop: "s+e.what());
}
}
exit(0);
}
}
return *this;
}