| 1 | // |
| 2 | // UDPClient.cpp |
| 3 | // |
| 4 | // Library: Net |
| 5 | // Package: UDP |
| 6 | // Module: UDPClient |
| 7 | // |
| 8 | // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. |
| 9 | // and Contributors. |
| 10 | // |
| 11 | // SPDX-License-Identifier: BSL-1.0 |
| 12 | // |
| 13 | |
| 14 | |
| 15 | #include "Poco/Net/UDPClient.h" |
| 16 | #include "Poco/ErrorHandler.h" |
| 17 | |
| 18 | |
| 19 | namespace Poco { |
| 20 | namespace Net { |
| 21 | |
| 22 | |
| 23 | UDPClient::UDPClient(const std::string& address, Poco::UInt16 port, bool listen): |
| 24 | _address(address, port), |
| 25 | _pThread(0), |
| 26 | _stop(false) |
| 27 | { |
| 28 | _socket.bind(SocketAddress(address, 0), true, true); |
| 29 | _socket.setReuseAddress(true); |
| 30 | _socket.setReusePort(true); |
| 31 | _socket.connect(_address); |
| 32 | _socket.setBlocking(true); |
| 33 | if (listen) |
| 34 | { |
| 35 | _pThread = new Thread; |
| 36 | _pThread->start(*this); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | |
| 41 | UDPClient::~UDPClient() |
| 42 | { |
| 43 | _stop = true; |
| 44 | if (_pThread) |
| 45 | { |
| 46 | _pThread->join(); |
| 47 | delete _pThread; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | |
| 52 | void UDPClient::run() |
| 53 | { |
| 54 | Poco::Timespan span(250000); |
| 55 | while (!_stop) |
| 56 | { |
| 57 | if (_socket.poll(span, Socket::SELECT_READ)) |
| 58 | { |
| 59 | try |
| 60 | { |
| 61 | char buffer[sizeof(Poco::UInt32)*2]; |
| 62 | int n = _socket.receiveBytes(buffer, sizeof(buffer)); |
| 63 | if (n >= sizeof(Poco::Int32)) handleResponse(buffer, n); |
| 64 | } |
| 65 | catch (Exception& exc) |
| 66 | { |
| 67 | ErrorHandler::handle(exc); |
| 68 | } |
| 69 | catch (std::exception& exc) |
| 70 | { |
| 71 | ErrorHandler::handle(exc); |
| 72 | } |
| 73 | catch (...) |
| 74 | { |
| 75 | ErrorHandler::handle(); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | |
| 82 | int UDPClient::handleResponse(char* buffer, int length) |
| 83 | { |
| 84 | Poco::Int32 count = *reinterpret_cast<Poco::Int32*>(buffer); |
| 85 | if (count > 0) _dataBacklog = count; |
| 86 | else if (count < 0) _errorBacklog = count; |
| 87 | return count; |
| 88 | } |
| 89 | |
| 90 | |
| 91 | } } // namespace Poco::Net |
| 92 | |