tcpServer.cpp (1089B)
1 #include "tcpServer.h" 2 3 #include "logging.h" 4 5 #include "../ptypes/pinet.h" 6 7 namespace ptypes 8 { 9 class exception; 10 } 11 12 namespace networkLib 13 { 14 TcpServer::TcpServer(OnConnectedFunc _onConnected, const int _tcpPort) : TcpConnection(std::move(_onConnected)), m_port(_tcpPort) 15 { 16 start(); 17 } 18 19 void TcpServer::threadFunc() 20 { 21 ptypes::ipstmserver tcpListener; 22 23 LOGNET(LogLevel::Info, "Waiting for incoming connections on TCP port " << m_port); 24 25 tcpListener.bindall(m_port); 26 27 ptypes::ipstream* stream = new ptypes::ipstream(); 28 29 while (!exit()) 30 { 31 try 32 { 33 if (tcpListener.serve(*stream, -1, 1000)) 34 { 35 LOGNET(LogLevel::Info, "Client " << static_cast<const char*>(ptypes::iptostring(stream->get_ip())) << ":" << stream->get_port() << " connected"); 36 onConnected(stream); 37 stream = new ptypes::ipstream(); 38 } 39 } 40 catch (ptypes::exception* e) 41 { 42 LOGNET(LogLevel::Warning, "Network Error: " << static_cast<const char*>(e->get_message())); 43 delete e; 44 } 45 } 46 47 LOGNET(LogLevel::Info, "TCP server shutdown"); 48 delete stream; 49 stream = nullptr; 50 } 51 }