示例#1
0
void ServicePort::handle(Acceptor_ptr acceptor, boost::asio::ip::tcp::socket* socket, const boost::system::error_code& error)
{
	if(!error)
	{
		if(m_services.empty())
		{
#ifdef __DEBUG_NET__
			std::clog << "[Error - ServerPort::handle] No services running!" << std::endl;
#endif
			return;
		}

		boost::system::error_code error;
		const boost::asio::ip::tcp::endpoint ip = socket->remote_endpoint(error);

		uint32_t remoteIp = 0;
		if(!error)
			remoteIp = htonl(ip.address().to_v4().to_ulong());

		Connection_ptr connection;
		if(remoteIp && ConnectionManager::getInstance()->acceptConnection(remoteIp) &&
			(connection = ConnectionManager::getInstance()->createConnection(
			socket, m_io_service, shared_from_this())))
		{
			if(m_services.front()->isSingleSocket())
				connection->handle(m_services.front()->makeProtocol(connection));
			else
				connection->accept();
		}
		else if(socket->is_open())
		{
			boost::system::error_code error;
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);

			socket->close(error);
			delete socket;
		}

#ifdef __DEBUG_NET_DETAIL__
		std::clog << "handle - OK" << std::endl;
#endif
		accept(acceptor);
	}
	else if(error != boost::asio::error::operation_aborted)
	{
		PRINT_ASIO_ERROR("Handling");
		close();
		if(!m_pendingStart)
		{
			m_pendingStart = true;
			Scheduler::getInstance().addEvent(createSchedulerTask(5000, boost::bind(
				&ServicePort::service, boost::weak_ptr<ServicePort>(shared_from_this()),
				m_acceptors[acceptor], m_serverPort)));
		}
	}
#ifdef __DEBUG_NET__
	else
		std::clog << "[Error - ServerPort::handle] Operation aborted." << std::endl;
#endif
}
示例#2
0
void OutputMessagePool::configureOutputMessage(OutputMessage_ptr msg, Protocol* protocol, bool autosend)
{
	TRACK_MESSAGE(msg);
	msg->Reset();
	if(autosend)
	{
		msg->setState(OutputMessage::STATE_ALLOCATED);
		m_autoSendOutputMessages.push_back(msg);
	}
	else
		msg->setState(OutputMessage::STATE_ALLOCATED_NO_AUTOSEND);

	Connection_ptr connection = protocol->getConnection();
	assert(connection != NULL);

	msg->setProtocol(protocol);
	protocol->addRef();
#ifdef __DEBUG_NET_DETAIL__
	std::cout << "Adding reference to protocol - " << protocol << std::endl;
#endif
	msg->setConnection(connection);
	connection->addRef();
#ifdef __DEBUG_NET_DETAIL__
	std::cout << "Adding reference to connection - " << connection << std::endl;
#endif
	msg->setFrame(m_frameTime);
}
示例#3
0
void TCP::insert_connection(Connection_ptr conn)
{
  connections_.emplace(
      std::piecewise_construct,
      std::forward_as_tuple(conn->local(), conn->remote()),
      std::forward_as_tuple(conn));
}
示例#4
0
void Listener::connected(Connection_ptr conn) {
  debug("<Listener::connected> %s connected\n", conn->to_string().c_str());
  remove(conn);
  Expects(conn->is_connected());
  host_.add_connection(conn);
  on_connect_(conn);
}
示例#5
0
void ServicePort::onAccept(boost::asio::ip::tcp::socket* socket, const boost::system::error_code& error)
{
	if(!error)
	{
		if(m_services.empty())
		{
#ifdef __DEBUG_NET__
			std::cout << "Error: [ServerPort::accept] No services running!" << std::endl;
#endif
			return;
		}

		boost::system::error_code error;
		const boost::asio::ip::tcp::endpoint endpoint = socket->remote_endpoint(error);
		uint32_t remote_ip = 0;
		if(!error)
			remote_ip = htonl(endpoint.address().to_v4().to_ulong());

		if(remote_ip != 0/* && g_bans.acceptConnection(remote_ip)*/)
		{
			Connection_ptr connection = ConnectionManager::getInstance()->createConnection(socket, m_io_service, shared_from_this());
			if(m_services.front()->is_single_socket())
				connection->acceptConnection(m_services.front()->make_protocol(connection));
			else
				connection->acceptConnection();
		}
		else if(socket->is_open())
		{
			boost::system::error_code error;
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
			socket->close(error);
			delete socket;
		}
		accept();
	}
	else if(error != boost::asio::error::operation_aborted)
	{
		if(!m_pendingStart)
		{
			close();
			m_pendingStart = true;
			g_scheduler.addEvent(createSchedulerTask(15000,
				boost::bind(&ServicePort::openAcceptor, boost::weak_ptr<ServicePort>(shared_from_this()), m_serverPort)));
		}
	}
	else
	{
		#ifdef __DEBUG_NET__
		std::cout << "Error: [ServicePort::onAccept] Operation aborted." << std::endl;
		#endif
	}
}
示例#6
0
void Listener::remove(Connection_ptr conn) {
  debug2("<Listener::remove> Try remove %s\n", conn->to_string().c_str());
  auto it = syn_queue_.begin();
  while(it != syn_queue_.end())
  {
    if((*it) == conn)
    {
      syn_queue_.erase(it);
      debug("<Listener::remove> %s removed.\n", conn->to_string().c_str());
      return;
    }
    it++;
  }
}
void OutputMessagePool::send(OutputMessage_ptr msg)
{
	m_outputPoolLock.lock();
	OutputMessage::OutputMessageState state = msg->getState();
	m_outputPoolLock.unlock();

	if (state == OutputMessage::STATE_ALLOCATED_NO_AUTOSEND) {
		Connection_ptr connection = msg->getConnection();
		if (connection && !connection->send(msg)) {
			// Send only fails when connection is closing (or in error state)
			// This call will free the message
			msg->getProtocol()->onSendMessage(msg);
		}
	}
}
示例#8
0
void ServicePort::handle(boost::asio::ip::tcp::socket* socket, const boost::system::error_code& error)
{
	if(!error)
	{
		if(m_services.empty())
		{
			return;
		}

		boost::system::error_code error;
		const boost::asio::ip::tcp::endpoint ip = socket->remote_endpoint(error);

		uint32_t remoteIp = 0;
		if(!error)
			remoteIp = htonl(ip.address().to_v4().to_ulong());

		Connection_ptr connection;
		if(remoteIp && ConnectionManager::getInstance()->acceptConnection(remoteIp) &&
			(connection = ConnectionManager::getInstance()->createConnection(
			socket, m_io_service, shared_from_this())))
		{
			if(m_services.front()->isSingleSocket())
				connection->handle(m_services.front()->makeProtocol(connection));
			else
				connection->accept();
		}
		else if(socket->is_open())
		{
			boost::system::error_code error;
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);

			socket->close(error);
			delete socket;
		}

		accept();
	}
	else if(error != boost::asio::error::operation_aborted)
	{
		close();
		if(!m_pendingStart)
		{
			m_pendingStart = true;
			server.scheduler().addTask(SchedulerTask::create(Milliseconds(5000), std::bind(
				&ServicePort::onOpen, std::weak_ptr<ServicePort>(shared_from_this()), m_serverPort)));
		}
	}
}
示例#9
0
size_t TCP::send(Connection_ptr conn, const char* buffer, size_t n) {
  size_t written{0};
  auto packets = inet_.transmit_queue_available();

  debug2("<TCP::send> Send request for %u bytes\n", n);

  if(packets > 0) {
    written += conn->send(buffer, n, packets);
  }
  // if connection still can send (means there wasn't enough packets)
  // only requeue if not already queued
  if(conn->can_send() and !conn->is_queued()) {
    debug2("<TCP::send> Conn queued.\n");
    writeq.push_back(conn);
    conn->set_queued(true);
  }

  return written;
}
示例#10
0
void ServicePort::onAccept(boost::asio::ip::tcp::socket* socket, const boost::system::error_code& error)
{
	if (!error) {
		if (m_services.empty()) {
			return;
		}

		boost::system::error_code socketError;
		const boost::asio::ip::tcp::endpoint endpoint = socket->remote_endpoint(socketError);

		uint32_t remote_ip = 0;
		if (!socketError) {
			remote_ip = htonl(endpoint.address().to_v4().to_ulong());
		}

		if (remote_ip != 0 && g_bans.acceptConnection(remote_ip)) {
			Connection_ptr connection = ConnectionManager::getInstance()->createConnection(socket, m_io_service, shared_from_this());
			Service_ptr service = m_services.front();

			if (service->is_single_socket()) {
				connection->acceptConnection(service->make_protocol(connection));
			} else {
				connection->acceptConnection();
			}
		} else if (socket->is_open()) {
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, socketError);
			socket->close(socketError);
			delete socket;
		}

		accept();
	} else if (error != boost::asio::error::operation_aborted) {
		if (!m_pendingStart) {
			close();
			m_pendingStart = true;
			g_scheduler.addEvent(createSchedulerTask(15000,
			                     boost::bind(&ServicePort::openAcceptor, boost::weak_ptr<ServicePort>(shared_from_this()), m_serverPort)));
		}
	}
}
示例#11
0
void GateModule::ToClientData(const message& msg)
{
	UserContext ctx = get_userdata<UserContext>(msg);

	Connection_ptr pconn = nullptr;

	if (ctx.accountid != 0)
	{
		pconn = m_Connections->find_by_account(account_id::create(ctx.accountid));
	}
	else if (ctx.playerid != 0)
	{
		pconn = m_Connections->find_by_player( player_id::create(ctx.playerid));
	}

	if (pconn == nullptr)
	{
		return;
	}

	send_socket_message(pconn->getsocket_id(), msg.msg_data());
}
void OutputMessagePool::configureOutputMessage(OutputMessage_ptr msg, Protocol* protocol, bool autosend)
{
	msg->Reset();

	if (autosend) {
		msg->setState(OutputMessage::STATE_ALLOCATED);
		m_autoSendOutputMessages.push_back(msg);
	} else {
		msg->setState(OutputMessage::STATE_ALLOCATED_NO_AUTOSEND);
	}

	Connection_ptr connection = protocol->getConnection();
	assert(connection);

	msg->setProtocol(protocol);
	protocol->addRef();

	msg->setConnection(connection);
	connection->addRef();

	msg->setFrame(m_frameTime);
}
void OutputMessagePool::sendAll()
{
	std::lock_guard<std::recursive_mutex> lockClass(m_outputPoolLock);

	const int64_t dropTime = m_frameTime - 10000;
	const int64_t frameTime = m_frameTime - 10;

	for (OutputMessage_ptr omsg : m_toAddQueue) {
		const int64_t msgFrame = omsg->getFrame();
		if (msgFrame >= dropTime) {
			omsg->setState(OutputMessage::STATE_ALLOCATED);

			if (frameTime > msgFrame) {
				m_autoSendOutputMessages.push_front(omsg);
			} else {
				m_autoSendOutputMessages.push_back(omsg);
			}
		} else {
			//drop messages that are older than 10 seconds
			omsg->getProtocol()->onSendMessage(omsg);
		}
	}
	m_toAddQueue.clear();

	for (auto it = m_autoSendOutputMessages.begin(), end = m_autoSendOutputMessages.end(); it != end; it = m_autoSendOutputMessages.erase(it)) {
		OutputMessage_ptr omsg = *it;
		if (frameTime <= omsg->getFrame()) {
			break;
		}

		Connection_ptr connection = omsg->getConnection();
		if (connection && !connection->send(omsg)) {
			// Send only fails when connection is closing (or in error state)
			// This call will free the message
			omsg->getProtocol()->onSendMessage(omsg);
		}
	}
}
示例#14
0
void MessageProcessorManager::processMessage(
        Connection_ptr con,
        Message_ptr msg)
{
    // Obtiene el contenido y el descriptor del mensaje
    Holder holder = msg->holder();
    TypeDescriptor_ptr messageDescriptor = 
        holder.get_type_descriptor();

    // creates the key
    map_t::iterator it = m_processors.find(
            std::make_pair(con.get(), messageDescriptor));

    if (it != m_processors.end() && 
            !it->second.empty())
    {
        // Iterates over its associated processors
        processors_t::const_iterator pit = it->second.begin(); 

        for (; pit != it->second.end(); ++pit) 
        {
            const MessageProcessor_ptr processor = *pit;
            const ReflectivePath_t& path = processor->path();

            // Results
            TypeDescriptor_ptr descriptor = NULL;
            Holder value;

            bool res = followPath(messageDescriptor, holder, path, 
                    // Results
                    descriptor, value);

            if (res)
                processor->process(msg, value);
        }
    }
}
示例#15
0
// Called when data is received on python (outgoing connection)
void handle_python_on_read(Connection_ptr client, std::string response) {
  // Write response to our client
  client->write(response.data(), response.size());
}
示例#16
0
文件: DumpTool.cpp 项目: asenac/gsim
Dumper::Dumper(Connection_ptr connection_,
        TypeDescriptor_ptr message_,
        const QList< int >& path_, 
        QWidget * parent) :
    AbstractInputItem(connection_, message_, path_, parent), 
    m_data(new Data)
{
    const QString& id = connection_->name();

    QVBoxLayout * layout = new QVBoxLayout();
    layout->setMargin(0);

    qt::FormWidget * form = new qt::FormWidget();
    form->layout()->setMargin(0);
    layout->addWidget(form);

    m_data->filePrefix = new QLineEdit();
    QHBoxLayout * prefixLayout = new QHBoxLayout();
    m_data->browse = new QPushButton("&Browse");
    prefixLayout->addWidget(m_data->filePrefix);
    prefixLayout->addWidget(m_data->browse);
    prefixLayout->setMargin(0);
    form->addMediumField("File prefix", prefixLayout);
    
    m_data->suffixLength = new QSpinBox();
    m_data->suffixLength->setRange(1, 10); 
    m_data->suffixLength->setValue(4);
    form->addField("Suffix length", m_data->suffixLength);

    m_data->format = new QComboBox();
    m_data->format->addItem("Binary (*.bin)");
    m_data->format->addItem("Text (*.txt)");
    m_data->format->addItem("JSON (*.json)");
    form->addField("Format", m_data->format);

    m_data->multipleFiles = new QCheckBox();
    m_data->multipleFiles->setChecked(true);
    form->addField("Multiple files", m_data->multipleFiles);

    // start and stop button
    m_data->startStopButton = new qt::StartStopButton();
    m_data->startStopButton->setObjectName("start-stop");
    QHBoxLayout * startStopLayout = new QHBoxLayout();
    QSpacerItem * spacer = new QSpacerItem(40, 20, 
            QSizePolicy::Expanding, QSizePolicy::Minimum);
    startStopLayout->addItem(spacer);
    startStopLayout->addWidget(m_data->startStopButton);
    layout->addLayout(startStopLayout);

    setLayout(layout);

    connect(m_data->startStopButton,
            SIGNAL(clicked(bool)),
            this, SLOT(doStart(bool)));

    connect(m_data->startStopButton,
            SIGNAL(toggled(bool)),
            this, SLOT(setEnabled(bool)));

    connect(m_data->browse, SIGNAL(clicked()),
            this, SLOT(browse()));

    const std::string messageName (
            connection_->descriptor()->in()->get_descriptor_name(message_));
    QString defaultFile(id);
    defaultFile += ".";
    defaultFile += messageName.c_str();
    defaultFile += getFieldName(message_, path_);
    defaultFile += "-";
    m_data->filePrefix->setText(defaultFile);
}
示例#17
0
// Called when data is received on python (outgoing connection)
void handle_python_on_read(Connection_ptr client, const std::string& response) {
  // Write response to our client
  client->write(response);
}
示例#18
0
// Called when data is received on client (incoming connection)
void handle_client_on_read(Connection_ptr python, const std::string& request) {
  printf("Received [Client]: %s\n", request.c_str());
  // Write the request to our python server
  python->write(request);
}
示例#19
0
void Connection::default_on_disconnect(Connection_ptr conn, Disconnect) {
  if(!conn->is_closing())
    conn->close();
}