Path: blob/main/src/utils/iodevices/OutputDevice_Network.cpp
169678 views
/****************************************************************************/1// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo2// Copyright (C) 2006-2025 German Aerospace Center (DLR) and others.3// This program and the accompanying materials are made available under the4// terms of the Eclipse Public License 2.0 which is available at5// https://www.eclipse.org/legal/epl-2.0/6// This Source Code may also be made available under the following Secondary7// Licenses when the conditions for such availability set forth in the Eclipse8// Public License 2.0 are satisfied: GNU General Public License, version 29// or later which is available at10// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html11// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later12/****************************************************************************/13/// @file OutputDevice_Network.cpp14/// @author Michael Behrisch15/// @author Daniel Krajzewicz16/// @author Felix Brack17/// @date 200618///19// An output device for TCP/IP Network connections20/****************************************************************************/212223// ==========================================================================24// included modules25// ==========================================================================26#include <config.h>2728#include <thread>29#include <chrono>30#include <vector>31#include "OutputDevice_Network.h"32#include "foreign/tcpip/socket.h"33#include "utils/common/ToString.h"343536// ==========================================================================37// method definitions38// ==========================================================================39OutputDevice_Network::OutputDevice_Network(const std::string& host,40const int port) : OutputDevice(0, host + ":" + toString(port)) {41mySocket = new tcpip::Socket(host, port);42for (int wait = 1; wait < 10; wait += 1) {43try {44mySocket->connect();45break;46} catch (tcpip::SocketException& e) {47if (wait == 9) {48throw IOError(toString(e.what()) + " (host: " + host + ", port: " + toString(port) + ")");49}50std::this_thread::sleep_for(std::chrono::seconds(wait));51}52}53}545556OutputDevice_Network::~OutputDevice_Network() {57mySocket->close();58delete mySocket;59}606162std::ostream&63OutputDevice_Network::getOStream() {64return myMessage;65}666768void69OutputDevice_Network::postWriteHook() {70const std::string toSend = myMessage.str();71myMessage.str("");72if (toSend.empty() || !mySocket->has_client_connection()) {73return;74}75std::vector<unsigned char> msg;76msg.insert(msg.end(), toSend.begin(), toSend.end());77try {78mySocket->send(msg);79} catch (const tcpip::SocketException& e) {80mySocket->close();81throw IOError(e.what());82}83}848586/****************************************************************************/878889