1 | // |
---|---|
2 | // EchoServer.cpp |
3 | // |
4 | // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. |
5 | // and Contributors. |
6 | // |
7 | // SPDX-License-Identifier: BSL-1.0 |
8 | // |
9 | |
10 | |
11 | #include "EchoServer.h" |
12 | #include "Poco/Net/StreamSocket.h" |
13 | #include "Poco/Net/SocketAddress.h" |
14 | #include "Poco/Timespan.h" |
15 | #include <iostream> |
16 | |
17 | |
18 | using Poco::Net::Socket; |
19 | using Poco::Net::StreamSocket; |
20 | using Poco::Net::SocketAddress; |
21 | |
22 | |
23 | EchoServer::EchoServer(): |
24 | _socket(SocketAddress()), |
25 | _thread("EchoServer"), |
26 | _stop(false) |
27 | { |
28 | _thread.start(*this); |
29 | _ready.wait(); |
30 | } |
31 | |
32 | |
33 | EchoServer::EchoServer(const Poco::Net::SocketAddress& address): |
34 | _socket(address), |
35 | _thread("EchoServer"), |
36 | _stop(false) |
37 | { |
38 | _thread.start(*this); |
39 | _ready.wait(); |
40 | } |
41 | |
42 | |
43 | EchoServer::~EchoServer() |
44 | { |
45 | _stop = true; |
46 | _thread.join(); |
47 | } |
48 | |
49 | |
50 | Poco::UInt16 EchoServer::port() const |
51 | { |
52 | return _socket.address().port(); |
53 | } |
54 | |
55 | |
56 | void EchoServer::run() |
57 | { |
58 | _ready.set(); |
59 | Poco::Timespan span(250000); |
60 | while (!_stop) |
61 | { |
62 | if (_socket.poll(span, Socket::SELECT_READ)) |
63 | { |
64 | StreamSocket ss = _socket.acceptConnection(); |
65 | try |
66 | { |
67 | char buffer[256]; |
68 | int n = ss.receiveBytes(buffer, sizeof(buffer)); |
69 | while (n > 0 && !_stop) |
70 | { |
71 | ss.sendBytes(buffer, n); |
72 | n = ss.receiveBytes(buffer, sizeof(buffer)); |
73 | } |
74 | } |
75 | catch (Poco::Exception& exc) |
76 | { |
77 | std::cerr << "EchoServer: "<< exc.displayText() << std::endl; |
78 | } |
79 | } |
80 | } |
81 | } |
82 | |
83 |