1 | // |
2 | // UDPEchoServer.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 "UDPEchoServer.h" |
12 | #include "Poco/Net/SocketAddress.h" |
13 | #include "Poco/Timespan.h" |
14 | #include <iostream> |
15 | |
16 | |
17 | using Poco::Net::Socket; |
18 | using Poco::Net::DatagramSocket; |
19 | using Poco::Net::SocketAddress; |
20 | using Poco::Net::IPAddress; |
21 | |
22 | |
23 | UDPEchoServer::UDPEchoServer(): |
24 | _thread("UDPEchoServer" ), |
25 | _stop(false) |
26 | { |
27 | _socket.bind(SocketAddress(), true); |
28 | _thread.start(*this); |
29 | _ready.wait(); |
30 | } |
31 | |
32 | |
33 | UDPEchoServer::UDPEchoServer(const SocketAddress& sa): |
34 | _thread("UDPEchoServer" ), |
35 | _stop(false) |
36 | { |
37 | _socket.bind(sa, true); |
38 | _thread.start(*this); |
39 | _ready.wait(); |
40 | } |
41 | |
42 | |
43 | UDPEchoServer::~UDPEchoServer() |
44 | { |
45 | _stop = true; |
46 | _thread.join(); |
47 | } |
48 | |
49 | |
50 | Poco::UInt16 UDPEchoServer::port() const |
51 | { |
52 | return _socket.address().port(); |
53 | } |
54 | |
55 | |
56 | void UDPEchoServer::run() |
57 | { |
58 | Poco::Timespan span(250000); |
59 | while (!_stop) |
60 | { |
61 | _ready.set(); |
62 | if (_socket.poll(span, Socket::SELECT_READ)) |
63 | { |
64 | try |
65 | { |
66 | char buffer[256]; |
67 | SocketAddress sender; |
68 | int n = _socket.receiveFrom(buffer, sizeof(buffer), sender); |
69 | n = _socket.sendTo(buffer, n, sender); |
70 | } |
71 | catch (Poco::Exception& exc) |
72 | { |
73 | std::cerr << "UDPEchoServer: " << exc.displayText() << std::endl; |
74 | } |
75 | } |
76 | } |
77 | } |
78 | |
79 | |
80 | SocketAddress UDPEchoServer::address() const |
81 | { |
82 | return _socket.address(); |
83 | } |
84 | |