Last active
January 17, 2020 12:26
-
-
Save plusangel/f52a65a082f15b9237af22d59a08b643 to your computer and use it in GitHub Desktop.
Poco echo TCPServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.0.0) | |
project(tcp_server VERSION 0.1 | |
DESCRIPTION "Poco echo TCPServer") | |
set(CMAKE_CXX_STANDARD 17) | |
find_package(Poco REQUIRED Foundation Net) | |
# check if Poco library was found | |
if(Poco_FOUND) | |
message ("Poco library found.") | |
else() | |
message (FATAL_ERROR "Cannot find Poco library.") | |
endif() | |
add_executable(tcp_server main.cpp) | |
target_link_libraries(tcp_server Poco::Foundation Poco::Net) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Poco/Net/Socket.h" | |
#include "Poco/Net/TCPServer.h" | |
#include "Poco/Net/TCPServerConnection.h" | |
#include "Poco/Net/TCPServerConnectionFactory.h" | |
#include "Poco/Net/TCPServerParams.h" | |
#include <iostream> | |
class newConnection : public Poco::Net::TCPServerConnection { | |
public: | |
newConnection(const Poco::Net::StreamSocket &s) | |
: Poco::Net::TCPServerConnection(s) {} | |
void run() override { | |
Poco::Net::StreamSocket &ss = socket(); | |
try { | |
char buffer[256]; | |
int n = ss.receiveBytes(buffer, sizeof(buffer)); | |
std::cout << "Received: " << buffer; | |
while (n > 0) { | |
ss.sendBytes(buffer, n); | |
n = ss.receiveBytes(buffer, sizeof(buffer)); | |
std::cout << "Received: " << buffer; | |
} | |
} catch (Poco::Exception &exc) { | |
std::cerr << "EchoConnection: " << exc.displayText() << std::endl; | |
} | |
} | |
}; | |
int main() { | |
// Create the server socket to listen | |
Poco::Net::ServerSocket socket(1234); | |
// Configure some server parameters | |
Poco::Net::TCPServerParams *pParams = new Poco::Net::TCPServerParams(); | |
pParams->setMaxThreads(4); | |
pParams->setMaxQueued(4); | |
pParams->setThreadIdleTime(100); | |
// Create the server | |
Poco::Net::TCPServer myserver( | |
new Poco::Net::TCPServerConnectionFactoryImpl<newConnection>(), socket, | |
pParams); | |
myserver.start(); | |
while (true) | |
; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment