OpenAstra
 
Loading...
Searching...
No Matches
tcpserver.hpp
1#ifndef TCPSERVER_H
2#define TCPSERVER_H
3
4#include <memory>
5#include <vector>
6
7#include "socketdevice.h"
8
9class TcpServer
10{
11public:
12 TcpServer(int listen_port, const std::string& listen_on )
13 : _socket( std::make_unique<SocketDevice>( SocketDevice::tcpip, listen_on, listen_port, "", 0 ) )
14 {
15 // Setting SO_REUSEADDR ensure that upon termination, the socket can be reopened without the "bind" error
16 _socket->setReuseAddr();
17 }
18 virtual ~TcpServer() {}
19
20 bool initialize() {
21 if ( _socket->initialize() )
22 {
23 if ( _socket->bind() )
24 {
25 if ( _socket->listen() )
26 {
27 return true;
28 }
29 }
30 }
31 return false;
32 }
33
34 void shutdown() {
35 _socket->shutdown();
36 }
37
38 bool isReady() {
39 return _socket->isInitialized();
40 }
41
42 std::vector<std::unique_ptr<SocketDevice>> checkNewClients() {
43 std::vector<std::unique_ptr<SocketDevice>> new_clients;
44 // Accept all incoming sockets:
45 while ( _socket->hasIncomingData() )
46 {
47 std::unique_ptr<SocketDevice> new_client = _socket->accept();
48 if ( new_client != NULL )
49 new_clients.push_back( std::move(new_client) );
50 }
51 return new_clients;
52 }
53
54private:
55 std::unique_ptr<SocketDevice> _socket;
56};
57
58#endif // TCPSERVER_H