-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqotd.cc
77 lines (60 loc) · 1.44 KB
/
qotd.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "ClientSocket.hh"
#include "Server.hh"
#include <signal.h>
#include <fstream>
#include <random>
#include <string>
#include <vector>
Server server;
void handleExitSignal( int /* signal */ )
{
server.close();
}
void unescapeQuote( std::string& quote )
{
std::size_t position = 0;
std::string target = "\\n";
std::string replacement = "\n";
while( ( position = quote.find( target, position ) ) != std::string::npos )
{
quote.replace( position, target.length(), replacement );
position += replacement.length();
}
}
std::vector<std::string> readQuotes( const std::string& filename )
{
std::ifstream in( filename );
if( !in )
return {};
std::vector<std::string> quotes;
std::string line;
while( std::getline( in, line ) )
{
unescapeQuote( line );
quotes.push_back( line );
}
return quotes;
}
int main( int argc, char** argv )
{
std::vector<std::string> quotes;
if( argc > 1 )
quotes = readQuotes( argv[1] );
else
quotes = { "Sorry, no quote today, mate.\n" };
std::random_device rd;
std::mt19937 rng( rd() );
std::uniform_int_distribution<std::size_t> distribution( 0, quotes.size() - 1 );
signal( SIGINT, handleExitSignal );
server.setPort( 1041 );
server.onAccept( [&] ( std::weak_ptr<ClientSocket> socket )
{
if( auto s = socket.lock() )
{
s->write( quotes.at( distribution( rng ) ) );
s->close();
}
} );
server.listen();
return 0;
}