Exemple #1
0
void P2PNetworkInterface::send() {
	MessagePtr msg;
	stringstream info;
	uint64_t transmissionDuration;
	double rate;

	if (!connectedInterface) {
		info << "*** WARNING *** [block " << hostBlock->blockId << ",interface " << globalId <<"] : trying to send a Message but no interface connected";
		BaseSimulator::getScheduler()->trace(info.str());
		return;
	}

	if (outgoingQueue.size()==0) {
		info << "*** ERROR *** [block " << hostBlock->blockId << ",interface " << globalId <<"] : The outgoing buffer of this interface should not be empty !";
		BaseSimulator::getScheduler()->trace(info.str());
		exit(EXIT_FAILURE);
	}

	msg = outgoingQueue.front();
	outgoingQueue.pop_front();

	rate = dataRate - dataRateVariability + (generator()/(double)RAND_MAX) * 2 * dataRateVariability;
	transmissionDuration = (msg->size()*8000000ULL)/rate;
	messageBeingTransmitted = msg;
	messageBeingTransmitted->sourceInterface = this;
	messageBeingTransmitted->destinationInterface = connectedInterface;

	availabilityDate = BaseSimulator::getScheduler()->now()+transmissionDuration;
	//info << "*** sending (interface " << localId << " of block " << hostBlock->blockId << ")";
	//getScheduler()->trace(info.str());

	BaseSimulator::getScheduler()->schedule(new NetworkInterfaceStopTransmittingEvent(BaseSimulator::getScheduler()->now()+transmissionDuration, this));
}
Exemple #2
0
void Client::receiveMessages()
{
	while(d->msgqueue->isPending()) {
		MessagePtr msg = d->msgqueue->getPending();

		if(d->session.isNull()) {
			// No session? We must be in the login phase
			if(msg->type() == protocol::MSG_COMMAND)
				emit loginMessage(msg);
			else
				log(Log().about(Log::Level::Warn, Log::Topic::RuleBreak).message(
					QString("Got non-login message (type=%1) in login state").arg(msg->type())
					));

		} else {

			// Enforce origin ID, except when receiving a snapshot
			if(d->session->initUserId() != d->id)
				msg->setContextId(d->id);

			if(isHoldLocked())
				d->holdqueue << msg;
			else
				d->session->handleClientMessage(*this, msg);
		}
	}
}
void AprilServer::onProtobufMessage(const muduo::net::TcpConnectionPtr& conn,
        const MessagePtr& message,
        muduo::Timestamp time)
{

    const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
    const google::protobuf::FieldDescriptor* id_field = descriptor->FindFieldByName("id");
    const google::protobuf::FieldDescriptor* sync_field = descriptor->FindFieldByName("sync");

    const google::protobuf::Reflection* reflection = message->GetReflection();
    int32_t id = reflection->GetInt32(*message, id_field);
    bool sync = reflection->GetBool(*message, sync_field);
    LOG_INFO << "receive - id " << id << " sync " << sync;

    if (_sync && sync) {
        _dict->swap_dict();
        _sync = false;
    }

    april::response mess;
    int value = 0;
    _dict->seek(id, &value);
    mess.set_id(value);
    mess.set_sync(_sync);
    _codec.send(conn, mess);
    
}
Exemple #4
0
Arcus::PythonMessage::PythonMessage(const MessagePtr& message)
{
    _shared_message = message;
    _message = message.get();
    _reflection = message->GetReflection();
    _descriptor = message->GetDescriptor();
}
Exemple #5
0
void ProxyServer::sendMsgQueue(const MessagePtr& message,std::string title)
{
	std::string msgname = message->GetTypeName();
	std::string titlename = "push:" + msgname;
	std::string value = message->DebugString();	
	LOG4CXX_INFO(log4cxx::Logger::getLogger(PROXYSERVER),value);
}
Exemple #6
0
LocalFork::MessageAction LocalFork::handleReceivedMessage(MessagePtr msg, const AffectedArea &area)
{
	// No local fork: nothing to do. It is possible that we get a message from ourselves
	// that is not in the local fork, but this is not an error. It could happen when
	// playing back recordings, for example.
	if(_messages.isEmpty())
		return CONCURRENT;

	// Check if this is our own message that has finished its roundtrip
	if(msg->contextId() == _messages.first()->contextId()) {
		if(msg.equals(_messages.first())) {
			_messages.removeFirst();
			_areas.removeFirst();
			return ALREADYDONE;

		} else {
			// Unusual, but not an error. This can happen when the layer is locked while drawing
			// or when an operator performs some function on behalf the user.
			qWarning("local fork out of sync: discarding...");
			clear();
			return ROLLBACK;
		}
	}

	// OK, so this is another user's message. Check if it is concurrent
	for(const AffectedArea &a : _areas) {
		if(!area.isConcurrentWith(a)) {
			return ROLLBACK;
		}
	}

	return CONCURRENT;
}
Exemple #7
0
void Client::flush()
{
  while (mRunning)
    {
      // waits for messages to send
      boost::unique_lock<boost::mutex> lock(mWMutex);
      while (mWriteQ.empty() && mRunning)
	mWCond.wait(lock);

      if (mRunning)
	{
	  // get and remove next item
	  MessagePtr msg = mWriteQ.front();
	  mWriteQ.pop_front();
	  
	  // send it to the thread, but wait for other writes to finish
	  mWSMutex.lock();
	  boost::asio::async_write(mSocket,
				   boost::asio::buffer(msg->raw(),
						       msg->rawLength()),
				   boost::bind(&Client::onWritten,
					       this,
					       boost::asio::placeholders::error));
	}
    }
    printf("Done flushing...\n");
}
    void
    api ()
    {
      if ((current_.status == Protocol::TS_COMMITED ||
           current_.status == Protocol::TS_ABORTED) &&
          separation_duration_ == 0) // no transaction in progress
      {
        // start new transaction

        // Note that in_ is already locked by Scheduler

        MessagePtr m (in_.front ());
        in_.pop ();

        if (typeid (*m) == typeid (Send))
        {
          send_ = SendPtr (dynamic_cast<Send*> (m.release ()));
        }
        else
        {
          // cerr << "Expecting Send but received " << typeid (*m).name ()
          //      << endl;

          ::abort ();
        }

        current_.id++;
        current_.status = Protocol::TS_BEGIN;

        initiated_ = true;

        // if (trace_) cerr << "starting transaction with id " << current_.id
        //                  << endl;
      }
    }
void Server::OnMessage(ConnectionHandle connection, MessagePtr data)
{   
    Urho3D::MutexLock lock(mutexEvents_);

    ConnectionPtr connectionPtr = server_->get_con_from_hdl(connection);

    if (data->get_opcode() == websocketpp::frame::opcode::TEXT)
    {
        String textMsg(data->get_payload().c_str());
        LogInfo("[WebSocketServer]: on_utf8_message: size=" + String(textMsg.Length()) + " msg=" + textMsg);
    }
    else if (data->get_opcode() == websocketpp::frame::opcode::BINARY)
    {
        const std::string &payload = data->get_payload();
        if (payload.size() == 0)
        {
            LogError("[WebSocketServer]: Received 0 sized payload, ignoring");
            return;
        }
        SocketEvent *event = new SocketEvent(connectionPtr, SocketEvent::Data);
        event->data = DataSerializerPtr(new kNet::DataSerializer(payload.size()));
        event->data->AddAlignedByteArray(&payload[0], payload.size());

        events_.Push(event);
    }
}
Exemple #10
0
void print_introspection(MessagePtr message, const std::string& prefix) {
  if (!message->hasInstance()) {
    std::cout << "No instance!" << std::endl;
  }

  for(Message::const_iterator it = message->begin(); it != message->end(); ++it) {
    FieldPtr field = *it;

    std::cout << prefix << std::string(field->getDataType()) << " " << std::string(field->getName()) << " = ";
    if (field->isContainer()) std::cout << "[";

    if (field->isMessage()) {
      std::cout << std::endl;
      for(std::size_t i = 0; i < field->size(); i++) {
        MessagePtr expanded = field->expand(i);
        if (!expanded) {
          std::cout << prefix << "    (unknown)" << std::endl;
          continue;
        }
        print_introspection(expanded, prefix + "    ");
      }
      std::cout << prefix;
    } else {
      for(std::size_t i = 0; i < field->size(); i++) {
        if (i > 0) std::cout << ", ";
        std::cout << field->as<std::string>(i);
      }
    }
    if (field->isContainer()) std::cout << "]";
    std::cout << std::endl;
  }
}
Exemple #11
0
void 
NetServer::onStateMessage( MessagePtr m )
{
	K_ASSERT( m.Get() != 0 );

	NetStateMessage* nsm = static_cast<NetStateMessage*>( m.Get() );

	switch ( nsm->state )
	{
	case NetStateMessage::TCP_CLOSED:
		{
			NetGroupMap::iterator i = m_groups.find( nsm->groupId );

			if ( i != m_groups.end() )
			{
				NetGroup* group = i->second;

				if ( group != 0 )
				{
					group->Leave( nsm->connectionId );
				}
			}	
		}
		break;
	}

	m_listener->Notify( m );
}
Exemple #12
0
void Peer::HandleResponses(WMessagePtr pWMsg)
{
	MessagePtr pMsg = pWMsg->GetMsg();

	// get the peer list if given in message
	std::vector<RemotePeers> peerList = pMsg->m_peerList;
	if( peerList.size() > 0 ) {
		long ts = pMsg->m_timestamp;
		this->HandlePeerList(peerList, ts);
	}

	// see if it is a task message
	if( pMsg->IsTaskMessage() ) {
		int msgTaskId = pMsg->m_taskId;
		// get the task and forward the message
		std::map<int, TaskPtr>::iterator it;
		it = m_taskList.find(msgTaskId);
		if( it != m_taskList.end() ) {
			TaskPtr pTask = (*it).second;
			pTask->GetMessageQueue()->PutMessage(pWMsg);
		}
		else {
			Log(CONSOLE, L"No Task Related to Task Response Message Received for taskId: %d\n", msgTaskId);
		}
		return;
	}

	switch(pMsg->m_respType) {
		case GET_ONLINE_RESP:
			HandleOnlineResp(pMsg);
			break;
		default:
			break;
	}
}
Exemple #13
0
	void send_all(const T& value) {
		MessagePtr msg =  std::make_shared<Message>(sizeof(T));

		msg->set_body_length(sizeof(T));
		std::memcpy(msg->body(), &value, sizeof(T));
		msg->encode_header();
		send_all(msg);	
	}
Exemple #14
0
void ArcnetIO::writeMessage( const MessagePtr& msg )
{
	if ( !isEnabled_ )
	{
		THROW_ERROR("Arcnet subsystem has not been enabled.");
	}

	this->send( msg->msg(), msg->length() );
}
Exemple #15
0
MessagePtr Message::Alloc(const char* data, uint32_t len)
{
    MessagePtr msg;
    if (len > 0)
    {
        msg.reset(new Message(data, len));
    }
    return msg;    
}
Exemple #16
0
MessagePtr Message::Alloc(uint32_t len)
{
    MessagePtr msg;
    if (len > 0)
    {
        msg.reset(new Message(len));
    }
    return msg;
}
Exemple #17
0
void Host::handleReceiveEvent(ENetEvent* event)
{
    ENetPacket* packet = event->packet;
    PeerPtr peer = (Peer*) event->peer->data;

    MessagePtr message = MessageCreate(0);
    message->setPacket(packet);

    onMessage(peer, message);
}
Exemple #18
0
void AsyncConnection::HandleConnect(const MessagePtr msg, const boost::system::error_code& e)
{
    if (!e)
    {
        m_app->HandleConnect(Connection::shared_from_this());
        Start();
        async_send(boost::asio::buffer(msg->Data(), msg->Length()),
                m_strand.wrap(boost::bind(&AsyncConnection::HandleSend, this,
                        msg, boost::asio::placeholders::error, false))); 
    }
}
Exemple #19
0
	void send(int conn_idx, const T& value) {
		// hack

		// MessagePtr msg =  std::make_shared<Message>(sizeof(T));
		MessagePtr msg = scene_write_msg;

		msg->set_body_length(sizeof(T));
		std::memcpy(msg->body(), &value, sizeof(T));
		msg->encode_header();
		send(conn_idx, msg);			
	}
Exemple #20
0
void LocalRulesManager::sendMessage(MessagePtr msg, enet_uint32 reliability)
{
	unsigned char* buf = m_buffer;
	msg->addToBuffer(buf);

	ENetPacket * packet = enet_packet_create (m_buffer, 
		msg->getSize(), 
		reliability);

	enet_host_broadcast (m_server, 0, packet);
	enet_host_flush (m_server);
}
void RemoteRulesManager::sendMessage(MessagePtr msg, enet_uint32 reliability)
{
	unsigned char* buf = m_buffer;
	msg->addToBuffer(buf);

	ENetPacket * packet = enet_packet_create (m_buffer, 
		msg->getSize(), 
		reliability);

	enet_peer_send (m_peer, 0, packet);
	enet_host_flush (m_client);
}
Exemple #22
0
		static MessagePtr Parse(const char* buf, int len, ErrorCode* error)
		{
			MessagePtr message;

			typedef google::protobuf::int32 int32;

			// check sum
			int32 expectedCheckSum = async::detail::AsInt32(buf + len - kHeaderLen);
			int32 checkSum = static_cast<int32>(0
				/*::adler32(1,
				reinterpret_cast<const Bytef*>(buf),
				static_cast<int>(len - kHeaderLen))*/);
			if (checkSum == expectedCheckSum)
			{
				// get message type name
				int32 nameLen = async::detail::AsInt32(buf);
				if (nameLen >= 2 && nameLen <= len - 2 * kHeaderLen)
				{
					std::string typeName(buf + kHeaderLen, buf + kHeaderLen + nameLen - 1);
					// create message object
					message.reset(CreateMessage(typeName));
					if (message)
					{
						// parse from buffer
						const char* data = buf + kHeaderLen + nameLen;
						int32 dataLen = len - nameLen - 2 * kHeaderLen;
						if (message->ParseFromArray(data, dataLen))
						{
							*error = kNoError;
						}
						else
						{
							*error = kParseError;
						}
					}
					else
					{
						*error = kUnknownMessageType;
					}
				}
				else
				{
					*error = kInvalidNameLen;
				}
			}
			else
			{
				*error = kCheckSumError;
			}

			return message;
		}
Exemple #23
0
void Peer::queueMessage(const MessagePtr& message, uint8 channel)
{
    if( !message ) return;
    message->prepare();

    int status = enet_peer_send(peer, channel, message->getPacket());

    if(status  != 0)
    {
        LogWarn("Error sending packet to peer '%s'", getHostName().c_str());
        return;
    }
}
Exemple #24
0
void RcfProtoServer::ProtoRpcEndCpp(
    std::pair<MessagePtr, MessagePtr> requestResponsePair,
    RcfProtoControllerPtr controllerPtr)
{
    MessagePtr requestPtr = requestResponsePair.first;
    MessagePtr responsePtr = requestResponsePair.second;

    RcfProtoSession & context = * controllerPtr->mpRcfSession;
    int byteSize = responsePtr->ByteSize();
    context.mResponseBuffer = RCF::ByteBuffer(byteSize);
    responsePtr->SerializeToArray(context.mResponseBuffer.getPtr(), (int) context.mResponseBuffer.getLength());
    context._Commit();
}
Exemple #25
0
void Actor::Main() {
    is_working_ = true;
    MessagePtr msg;
    while (mailbox_->Pop(msg)) {
        if (handlers_.find(msg->type()) != handlers_.end()) {
            handlers_[msg->type()](msg);
        } else if (handlers_.find(MsgType::Default) != handlers_.end()) {
            handlers_[MsgType::Default](msg);
        } else {
            Log::Fatal("Unexpected msg type\n");
        }
    }
}
 //-----------------------------------------------------------------------
 MessageResultPtr MessageResult::create(
                                        MessagePtr requestOrNotify,
                                        WORD errorCode,
                                        const char *reason
                                        )
 {
   MessageResultPtr pThis(new MessageResult);
   pThis->mID = requestOrNotify->messageID();
   pThis->mOriginalMethod = requestOrNotify->method();
   pThis->mTime = zsLib::now();
   pThis->mErrorCode = errorCode,
   pThis->mErrorReason = String(reason ? reason : "");
   return pThis;
 }
Exemple #27
0
void AsyncConnection::Send(const MessagePtr msg)
{
    if (is_open())
    {
        async_send(boost::asio::buffer(msg->Data(), msg->Length()),
                m_strand.wrap(boost::bind(&AsyncConnection::HandleSend, this,
                        msg, boost::asio::placeholders::error, true)));        
    }
    else
    {
        boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(m_ip), m_port);
        async_connect(endpoint, m_strand.wrap(boost::bind(&AsyncConnection::HandleConnect, this,
                msg, boost::asio::placeholders::error)));
    }
}
Exemple #28
0
void Client::receiveMessages()
{
	while(_msgqueue->isPending()) {
		MessagePtr msg = _msgqueue->getPending();

		if(_state == LOGIN) {
			if(msg->type() == protocol::MSG_LOGIN)
				emit loginMessage(msg);
			else
				logger::notice() << this << "Got non-login message (type=" << msg->type() << ") in login state";
		} else {
			handleSessionMessage(msg);
		}
	}
}
Exemple #29
0
void 
NetClient::Send( MessagePtr m )
{
	K_ASSERT( m.Get() != 0 );

	m_sendQ.Put( m );
}
Exemple #30
0
void 
NetServer::Send( MessagePtr m )
{
	K_ASSERT( m.Get() != 0 );

	m_sendQ.Put( m );
}