Ejemplo n.º 1
0
void PHXSimWrap::writeData(uint id, uint64_t addr, uint64_t clockcycle)
{
    PRINTFN("%s: id=%d addr=%#lx clock=%lu\n",__func__,id,addr,clockcycle);

    std::multimap< uint64_t, PacketPtr >::iterator it =
                    m_wr_pktMap.find( addr );
    assert( it != m_wr_pktMap.end() );

    PacketPtr    pkt   = it->second;

    m_wr_lat.sample( curTick() - pkt->dram_enter_time );

    PRINTFN("%s() `%s` addr=%#lx size=%d\n", __func__, pkt->cmdString().c_str(),
                                        (long)pkt->getAddr(), pkt->getSize());

    PhysicalMemory::doAtomicAccess( pkt );

    if ( pkt->needsResponse() ) {
        m_readyQ.push_back(pkt);
    } else {
        delete pkt;
    }

    m_wr_pktMap.erase( addr );
}
Ejemplo n.º 2
0
int FrontProtocol::Barrier()
{
   int tag;
   PacketPtr p;
   unsigned int countACKs = 0;

#if defined(CONTROL_STREAM_BLOCKING)
   cerr << "[FE] Entering barrier..." << endl;
   MRN_STREAM_RECV(mrnApp->stControl, &tag, p, TAG_ACK);
   p->unpack("%d", &countACKs);
   cerr << "[FE] Barrier received " << countACKs << " ACK's..." << endl;
#else
   for (int i=0; i<mrnApp->stControl->size(); i++)
   {
     int x = 0;
     MRN_STREAM_RECV(mrnApp->stControl, &tag, p, TAG_ACK);
     p->unpack("%d", &x);
     countACKs += x;
   }
#endif

   cerr << "[FE] Barrier broadcasting " << countACKs << " ACK's..." << endl;
   MRN_STREAM_SEND(mrnApp->stControl, TAG_ACK, "%d", countACKs);

   if (countACKs != mrnApp->stControl->size())
   {
      cerr << "[FE] ERROR: FrontProtocol::Barrier: " << countACKs << " ACKs received, expected " << mrnApp->stControl->size() << endl;
      return -1;
   }
   cerr << "[FE] Exiting barrier" << endl;
   return 0;
}
Ejemplo n.º 3
0
bool CGameServer::DispatchZoneServer(const PacketPtr& PktPtr, KeyRef krSocket)
{
	bool bRet = false;
	switch (PktPtr->GetEvent()) {
	case PAK_EVENT_LINK:
		{
			bRet = OnServerLink(static_cast<CPAKLink*>(PktPtr.Get()), krSocket);
		}
		break;
	case PAK_EVENT_UPDATE:
		{
			bRet = OnServerUpdate(static_cast<CPAKUpdate*>(PktPtr.Get()), krSocket);
		}
		break;
	case PAK_EVENT_UNLINK:
		{
			bRet = OnServerUnlink(PktPtr.Get(), krSocket);
		}
		break;
	default:
		{
			LOGV_WARN(m_FileLog, TF("[游戏服务器]%p无法识别的地图服务器信令包数据[event=%d]"), krSocket, PktPtr->GetEvent());
		}
	}
	return bRet;
}
Ejemplo n.º 4
0
        void EstablishmentManager::processCreated(EstablishmentStatePtr const &state)
        {
            state->calculateDHSecret();

            if(!state->verifyCreationSignature()) {
                I2P_LOG(m_log, warning) << "creation signature verification failed";
                state->setState(EstablishmentState::State::FAILURE);
                return;
            }

            const ByteArray& dhSecret = state->getDHSecret();
            SessionKey newKey(toSessionKey(dhSecret)), newMacKey;

            state->setSessionKey(newKey);

            copy(dhSecret.begin() + 32, dhSecret.begin() + 32 + 32, newMacKey.begin());
            state->setMacKey(newMacKey);

            Endpoint ep = state->getTheirEndpoint();
            PeerState ps(ep, state->getTheirIdentity().getHash());
            ps.setCurrentSessionKey(state->getSessionKey());
            ps.setCurrentMacKey(state->getMacKey());

            std::lock_guard<std::mutex> lock(m_context.peers.getMutex());
            m_context.peers.addPeer(std::move(ps));

            PacketPtr p = PacketBuilder::buildSessionConfirmed(state);
            p->encrypt(state->getSessionKey(), state->getMacKey());

            m_context.sendPacket(p);

            state->setState(EstablishmentState::State::CONFIRMED_SENT);
            post(state);
        }
Ejemplo n.º 5
0
        void OutboundMessageFragments::timerCallback(const boost::system::error_code& e, PeerState ps, uint32_t const msgId)
        {
            if(!e) {
                std::lock_guard<std::mutex> lock(m_mutex);

                auto itr = m_states.find(msgId);
                if(itr != m_states.end()) {
                    OutboundMessageState& oms = itr->second;

                    if(oms.getTries() > 5) {
                        m_states.erase(msgId);
                        return;
                    }

                    PacketBuilder::FragmentPtr frag = oms.getNextUnackdFragment();
                    if(frag) {
                        std::vector<PacketBuilder::FragmentPtr> fragList;
                        fragList.push_back(frag);

                        oms.markFragmentSent(fragList[0]->fragNum);

                        PacketPtr p = PacketBuilder::buildData(ps.getEndpoint(), false, CompleteAckList(), PartialAckList(), fragList);
                        p->encrypt(ps.getCurrentSessionKey(), ps.getCurrentMacKey());
                        m_context.sendPacket(p);

                        oms.incrementTries();

                        oms.getTimer().expires_at(oms.getTimer().expires_at() + boost::posix_time::time_duration(0, 0, 2));
                        oms.getTimer().async_wait(boost::bind(&OutboundMessageFragments::timerCallback, this, boost::asio::placeholders::error, ps, msgId));
                    }
                }
            }
        }
Ejemplo n.º 6
0
void RealmConnection::_complete_packet(PacketPtr packet_ptr)
{
	UT_DEBUGMSG(("RealmConnection::_complete_packet()\n"));
	int bytes_needed = packet_ptr->complete(m_buf.data(), m_buf.size());
	switch (bytes_needed)
	{
		case -1:
			UT_DEBUGMSG(("Error determining packet (type: 0x%x) completion state!\n", packet_ptr->type()));
			return;
		case 0:
			{
				UT_DEBUGMSG(("Read full packet\n"));
				UT_return_if_fail(packet_ptr->parse(m_buf.data(), m_buf.size()) != -1);
				m_packet_queue.push(packet_ptr);
				_receive();
			}
			break;
		default:
			UT_DEBUGMSG(("Need more data (%d bytes) for this packet...\n", bytes_needed));
			// read the needed number of bytes
			char* ptr = m_buf.prepare(bytes_needed);
			asio::async_read(m_socket, asio::buffer(ptr, bytes_needed),
							boost::bind(&RealmConnection::_complete, shared_from_this(),
								asio::placeholders::error, asio::placeholders::bytes_transferred, packet_ptr)
							);
			break;
	}
}
Ejemplo n.º 7
0
bool CGameServer::DispatchGateServer(const PacketPtr& PktPtr, KeyRef krSocket)
{
	bool bRet = false;
	switch (PktPtr->GetEvent()) {
	case PAK_EVENT_LINK:
		{
			bRet = OnServerLink(static_cast<CPAKLink*>(PktPtr.Get()), krSocket);
		}
		break;
	case PAK_EVENT_UPDATE:
		{
			bRet = OnServerUpdate(static_cast<CPAKUpdate*>(PktPtr.Get()), krSocket);
		}
		break;
	case PAK_EVENT_UNLINK:
		{
			bRet = OnServerUnlink(PktPtr.Get(), krSocket);
		}
		break;
	case PAK_EVENT_GAME_ID:
		{
			CPAKGameIdAck GameIdAck;
			GameIdAck.SetId((Int)m_ServerInfo.usId);
			GameIdAck.AdjustSize();
			m_NetworkPtr->Send(krSocket, GameIdAck);
		}
		break;
	default:
		{
			LOGV_WARN(m_FileLog, TF("[游戏服务器]%p无法识别的网关服务器信令包数据[event=%d]"), krSocket, PktPtr->GetEvent());
		}
	}
	return bRet;
}
Ejemplo n.º 8
0
        void OutboundMessageFragments::sendDataCallback(PeerState ps, uint32_t const msgId)
        {
            std::lock_guard<std::mutex> lock(m_mutex);

            auto itr = m_states.find(msgId);
            if(itr != m_states.end()) {
                OutboundMessageState& oms = itr->second;

                std::vector<PacketBuilder::FragmentPtr> fragList;
                auto fragment = oms.getNextFragment();

                if (fragment == nullptr) {
                    throw std::runtime_error("no ssu fragment when sending");
                }

                fragList.push_back(fragment);

                oms.markFragmentSent(fragList[0]->fragNum);

                PacketPtr p = PacketBuilder::buildData(ps.getEndpoint(), false, CompleteAckList(), PartialAckList(), fragList);
                p->encrypt(ps.getCurrentSessionKey(), ps.getCurrentMacKey());
                m_context.sendPacket(p);

                if(!oms.allFragmentsSent())
                    m_context.ios.post(boost::bind(&OutboundMessageFragments::sendDataCallback, this, ps, msgId));
            }
        }
Ejemplo n.º 9
0
bool CGameServer::DispatchGameDBServer(const PacketPtr& PktPtr, KeyRef krSocket)
{
	switch (PktPtr->GetEvent()) {
	case PAK_EVENT_LINKACK:
		{
			m_bGameDBLinked = true;

			NET_ADDR NetAddr;
			m_NetworkPtr->GetAddr(krSocket, NetAddr, false);
			m_pUIHandler->OnHandle(PAK_EVENT_LINK, reinterpret_cast<uintptr_t>(&NetAddr), DATA_INDEX_GAMEDB);
			LOG_INFO(m_FileLog, TF("[游戏服务器]收到游戏DB服务器注册回复包"));
		}
		break;
	case PAK_EVENT_UPDATEACK:
		{
			DEV_INFO(TF("[游戏服务器]收到游戏DB服务器更新回复包"));
		}
		break;
	case PAK_EVENT_UNLINKACK:
		{
			m_bGameDBLinked = false;
			LOG_INFO(m_FileLog, TF("[游戏服务器]收到游戏DB服务器注销回复包"));
		}
		break;
	case PAK_EVENT_LIVEACK:
		{
		}
		break;
	default:
		{
			LOGV_WARN(m_FileLog, TF("[游戏服务器]%p无法识别的游戏DB服务器信令包数据[event=%d]"), krSocket, PktPtr->GetEvent());
		}
	}
	return true;
}
Ejemplo n.º 10
0
int test_CountFilter( Network * net, const char * so_file )
{
    int retval, tag, recv_val=0;
    PacketPtr buf;
    std::string testname("test_Count"); 

    test->start_SubTest(testname);

    int filter_id = net->load_FilterFunc( so_file, "aggr_Count" );
    if( filter_id == -1 ){
        test->print("Stream::load_FilterFunc() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }

    Communicator * comm_BC = net->get_BroadcastCommunicator( );
    Stream * stream = net->new_Stream(comm_BC, filter_id, SFILTER_WAITFORALL);

    if( stream->send(PROT_COUNT, "") == -1 ){
        test->print("stream::send() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }
    if( stream->flush( ) == -1 ){
        test->print("stream::flush() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }

    retval = stream->recv(&tag, buf);
    assert( retval != 0 ); //shouldn't be 0, either error or block till data
    if( retval == -1){
        //recv error
        test->print("stream::recv() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }
    else{
        //Got data
        if( buf->unpack( "%d", &recv_val ) == -1 ){
            test->print("stream::unpack() failure\n", testname);
            return -1;
        }
        if( recv_val != (int)stream->size() ){
            char tmp_buf[256];
            sprintf(tmp_buf, "recv_val(%d) != NumEndPoints(%d). Failure.\n",
                    recv_val, stream->size( ) );
            test->print(tmp_buf, testname);
            test->end_SubTest(testname, MRNTEST_FAILURE);
            return -1;
        }
    }

    test->end_SubTest(testname, MRNTEST_SUCCESS);
    return 0;
}
Ejemplo n.º 11
0
void RfidReaderMac::addSelectHeader(PacketPtr packet, 
	NodeId receiverId) const
{
	RfidReaderMacDataPtr macData = RfidReaderMacData::create();
	macData->setType(RfidReaderMacData::Types_Select);
	macData->setSenderId(getNode()->getNodeId());
	macData->setReceiverId(receiverId);
	packet->setDoMaxTxPower(true);
	packet->addData(Packet::DataTypes_Link, *macData);
}
Ejemplo n.º 12
0
        void EstablishmentManager::sendRequest(EstablishmentStatePtr const &state)
        {
            PacketPtr p = PacketBuilder::buildSessionRequest(state);
            p->encrypt(state->getSessionKey(), state->getMacKey());

            m_context.sendPacket(p);

            state->setState(EstablishmentState::State::REQUEST_SENT);
            post(state);
        }
Ejemplo n.º 13
0
int test_CountOddsAndEvensFilter( Network * net, const char * so_file )
{
    int num_odds=0, num_evens=0, retval, tag=0;
    PacketPtr buf;
    std::string testname("test_CountOddsAndEvens"); 

    test->start_SubTest(testname);

    int filter_id = net->load_FilterFunc( so_file,
                                             "aggr_CountOddsAndEvens" );
    if( filter_id == -1 ){
        test->print("Stream::load_FilterFunc() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }

    Communicator * comm_BC = net->get_BroadcastCommunicator( );
    Stream * stream = net->new_Stream(comm_BC, filter_id, SFILTER_WAITFORALL);

    if( stream->send(PROT_COUNTODDSANDEVENS, "") == -1 ){
        test->print("stream::send() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }

    if( stream->flush( ) == -1 ){
        test->print("stream::flush() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }

    retval = stream->recv(&tag, buf);
    assert( retval != 0 ); //shouldn't be 0, either error or block till data
    if( retval == -1){
        //recv error
        test->print("stream::recv() failure\n", testname);
        test->end_SubTest(testname, MRNTEST_FAILURE);
        return -1;
    }
    else{
        //Got data
        if( buf->unpack( "%d %d", &num_odds, &num_evens ) == -1 ){
            test->print("stream::unpack() failure\n", testname);
            test->end_SubTest(testname, MRNTEST_FAILURE);
            return -1;
        }
        char tmp_buf[256];
        sprintf(tmp_buf, "num_odds = %d; num_evens = %d\n",
                num_odds, num_evens);
        test->print(tmp_buf, testname);
    }

    test->end_SubTest(testname, MRNTEST_SUCCESS);
    return 0;
}
Ejemplo n.º 14
0
bool SimulatorLink::sendData(PacketPtr data) {

    // Create a copy, or we get the really wierd situation where updating the number of
    // hops on one router will change all copies of the packet, even those in transit!

    PacketPtr ptr = std::make_shared<Packet>(data->getData(), data->getDataLength());

    sendQueue.push(ptr);

    return true;
}
Ejemplo n.º 15
0
PacketPtr RfidReaderMac::createAckPacket(NodeId destination) const
{
	RfidReaderMacDataPtr macData = RfidReaderMacData::create();
	macData->setType(RfidReaderMacData::Types_Ack);
	macData->setSenderId(getNode()->getNodeId());
	macData->setReceiverId(destination);

	PacketPtr packet = Packet::create();
	packet->setDoMaxTxPower(true);
	packet->addData(Packet::DataTypes_Link, *macData);
	return packet;
}
        bool Packetizer::putPacket(PacketPtr ptr) {
          bool result = false;
          //in case of stream is not mapped through stream_data element, discard packet
          if (_streams.find(ptr->getStreamIndex()) == _streams.end()) {
            return false;
          }

          if (_codec_overlap.find(_streams[ptr->getStreamIndex()].decoder->getCodecId()) == _codec_overlap.end()) {
            _codec_overlap[_streams[ptr->getStreamIndex()].decoder->getCodecId()] = 0;
          }
          result = processPacket(ptr);
          return result;
        }
void BridgeClassicToAMBATLM2<BUSWIDTH>::recvFunctional(PacketPtr pkt)
{
//	std::cout << "Called recvFunctional" << std::endl;
    tlm::tlm_generic_payload trans;
	if (pkt->isRead())
		trans.set_read();
	else if (pkt->isWrite())
		trans.set_write();
	trans.set_address(pkt->getAddr());
	trans.set_data_length(pkt->getSize());
//	trans.set_streaming_width(TBD);
	trans.set_data_ptr(pkt->getPtr<unsigned char>());
	debug_port->transport_dbg(static_cast<tlm::tlm_generic_payload &>(trans));

}
Ejemplo n.º 18
0
//--------------------------------------
bool CGameServer::OnUdpDispatch(const PacketPtr& PktPtr, PUDP_PARAM pUdp)
{
	// PUDP_PARAM->pCache == nullptr, 上层可以保存从底层申请的缓存数据
	// PUDP_PARAM->pCache, PUDP_PARAM->index是底层申请的缓存数据的起始地址和索引号
	// 如果上层保存缓存, 设置PUDP_PARAM->pData为nullptr通知网络底层
	// 释放缓存使用MObject::sMCFree(index, pCache)
	assert(PktPtr->GetEvent() == PAK_EVENT_LOGIN_SELECT_GAME);
	CPAKLoginSelectGame* pSelect = static_cast<CPAKLoginSelectGame*>(PktPtr.Get());
	if (SelectGame(pSelect) == false) {
		pSelect->SetAck(LOGIN_ERROR_NONE_GATE);
		m_NetworkPtr->SendTo(pUdp->krSocket, *pSelect, pUdp->NetAddr);
		LOG_INFO(m_FileLog, TF("[游戏服务器]游戏服务器收到客户端选择游戏服务器请求, 但是没有网关服务器"));
	}
	return true;
}
Ejemplo n.º 19
0
void Loopback::OnLocalNodeWritesToGroup(const PacketPtr packet)
{
    GScale::GroupCore::LocalNodeSetIdx_uuid::iterator it = this->gdao->findByUUID(packet.getReceiver().getNodeUUID());
    if(it != this->gdao->end<GScale::GroupCore::idxnode_nodeuuid>()){
        it->node.OnRead(this->groupc->getGroupAPI(), *packet);
    }
}
Ejemplo n.º 20
0
void CGameServerPlayer::QueueToCurrentComposite(CActor* actor, const PacketPtr& srcPacket)
{
	auto packet = srcPacket->Clone();
	packet->SetSourceId(actor->GetId());
	packet->SetTargetId(PLAYER_ID);
	m_currentComposite.AddPacket(packet->ToPacketData());
}
Ejemplo n.º 21
0
void RfidReaderMac::handlePacketSent(PacketPtr packet)
{
	if(isPacketType(packet, RfidReaderMacData::Types_Request)) {
		// Start a cycle
		m_currentSlotNumber = 0;
		RfidReaderMacDataPtr macData =
			boost::dynamic_pointer_cast<RfidReaderMacData>
			(packet->getData(Packet::DataTypes_Link));
		assert(macData.get() != 0);
		m_numberOfSlots = macData->getNumberOfSlots();
	} else if(isPacketType(packet, RfidReaderMacData::Types_Select)) {
		m_doResetSlot = true;
		// m_currentSlotNumber is already set to slot i+1, so
		// the resetSlotNumber should be slot i+2.  Thus, we
		// add one to currentSlotNumber.
		m_resetSlotNumber = m_currentSlotNumber + 1;
		/*
		cout << "slot: " << m_currentSlotNumber << " resetSlot: " <<
			m_resetSlotNumber << endl;
		*/
	} else if(isPacketType(packet, RfidReaderMacData::Types_Ack)) {
		if(isEnoughTimeForContentionCycle()) {
			startNextContentionCycle();
		}
	} else {
		unblockUpperQueues();
	}
}
Ejemplo n.º 22
0
void Player::HandlePacket( PacketPtr packet ) {
	if( packet->getDataSize() < 4 ) {
		LogConsole("Player sent packet size < 4");
		return;
	}

	ObjectPtr agent( m_agent.lock() );
	if( !agent ) {
		LogConsole( "Player agent deleted, deleting player." );
		Delete();
		return;
	}

	sf::Uint16 type0;
	(*packet) >> type0;

	switch( type0 ) {
		case ClientToServer::CLIENT_COMMAND:
			agent->HandlePacket( packet );
			break;
		default:
			LogConsole( "Player sent packet with type0=" + string_cast( type0 ) );
			break;
	}
}
Ejemplo n.º 23
0
/**
 * Automatically publishes all the streams that are queued in 'registeredStreams' to the back-ends.
 * return 0 on success; -1 otherwise.
 */
int FrontProtocol::AnnounceStreams()
{
   int tag, NumberOfStreams=0;
   PacketPtr p;

   /* Announce streams to the back-ends */
   unsigned int countACKs = 0;

   /* DEBUG 
   std::cout << "[FE] FrontProtocol::AnnounceStreams: Sending " << registeredStreams.size() << " streams" << std::endl; */

   /* Send the number of streams */
   NumberOfStreams = registeredStreams.size();
   MRN_STREAM_SEND(mrnApp->stControl, TAG_STREAM, "%d", registeredStreams.size());

   for (int i=0; i<NumberOfStreams; i++)
   {
      STREAM *st = registeredStreams.front();
      /* DEBUG
      std::cout << "[FE] FrontProtocol::AnnounceStreams: Publishing stream #" << st->get_Id() << " streams" << std::endl; */
      /* Send a message through every stream */
      MRN_STREAM_SEND(st, TAG_STREAM, "");
      /* Remove the stream from the queue */
      registeredStreams.pop();
   }
   /* Read ACKs */
#if defined(CONTROL_STREAM_BLOCKING)
   MRN_STREAM_RECV(mrnApp->stControl, &tag, p, TAG_ACK);
   p->unpack("%d", &countACKs);
#else
   for (int i=0; i<mrnApp->stControl->size(); i++)
   {
     int x = 0;
     MRN_STREAM_RECV(mrnApp->stControl, &tag, p, TAG_ACK);
     p->unpack("%d", &x);
     countACKs += x;
   }
#endif

   if (countACKs != mrnApp->stControl->size())
   {
      cerr << "[FE] Error announcing streams! (" << countACKs << " ACKs received, expected " << mrnApp->stControl->size() << ")" << endl;
      return -1;
   }
   return 0;
}
Ejemplo n.º 24
0
PacketPtr RfidReaderMac::createRequestPacket() const
{
	RfidReaderMacDataPtr macData = RfidReaderMacData::create();
	macData->setType(RfidReaderMacData::Types_Request);
	macData->setSenderId(getNode()->getNodeId());
	macData->setReceiverId(NodeId::broadcastDestination());
	// We must have at least: (1) a contention slot,
	// (2) a slot for the SELECT to be sent by the ready,
	// (3) a slot for the tag to reply with an app packet,
	// (4) a slot for the reader to reply with an ACK.
	assert(m_nextCycleNumberOfSlots >= 4);
	macData->setNumberOfSlots(m_nextCycleNumberOfSlots);
	PacketPtr packet = Packet::create();
	assert(m_currentAppReadPacket.get() != 0);
	packet->setTxPower(m_currentAppReadPacket->getTxPower());
	packet->addData(Packet::DataTypes_Link, *macData);
	return packet;
}
Ejemplo n.º 25
0
void RfidReaderMac::addGenericHeader(PacketPtr packet, 
	NodeId receiverId) const
{
	RfidReaderMacDataPtr macData = RfidReaderMacData::create();
	macData->setType(RfidReaderMacData::Types_Generic);
	macData->setSenderId(getNode()->getNodeId());
	macData->setReceiverId(receiverId);
	packet->addData(Packet::DataTypes_Link, *macData);
}
Ejemplo n.º 26
0
void ResourceManager::FillResourcePacket( sf::Uint32 id, PacketPtr packet ) const {
	std::map<sf::Uint32, const PacketPtr>::const_iterator iter( m_resources.find( id ) );

	if( iter == m_resources.end() ) {
		Die( "Could not find resource with ID: " + string_cast( id ) + "\n" );
	}

	packet->append( iter->second->getData(), iter->second->getDataSize() );
}
Ejemplo n.º 27
0
	bool processSocket(bool expectingPacket)
	{
		int len = pNextPacket_->recvFromEndPoint(socket_);
		if (len <= 0)
		{
			return this->checkSocketErrors(len, expectingPacket);
		}

		PacketPtr curPacket = pNextPacket_;
		pNextPacket_ = new TCPPacket();
		Address srcAddr = socket_.getRemoteAddress();
		Reason ret = this->processPacket(srcAddr, curPacket.get());

		if (ret != REASON_SUCCESS)
		{
			this->dispatcher().errorReporter().reportException(ret, srcAddr);
		}
		return true;
	}
Ejemplo n.º 28
0
void AbstractStream::packetLoop(AbstractStream *stream)
{
    while (stream->m_runPacketLoop) {
        stream->m_packetMutex.lock();

        if (stream->m_packets.isEmpty())
            stream->m_packetQueueNotEmpty.wait(&stream->m_packetMutex,
                                               THREAD_WAIT_LIMIT);

        if (!stream->m_packets.isEmpty()) {
            PacketPtr packet = stream->m_packets.dequeue();
            stream->processPacket(packet.data());
            stream->m_packetQueueSize -= packet->size;
            emit stream->notify();
        }

        stream->m_packetMutex.unlock();
    }
}
void ApplicationBarrierManager::handlePacket(PacketPtr packet, gadget::NodePtr node)
{
   vprDEBUG(gadgetDBG_RIM, vprDBG_HVERB_LVL)
         << clrOutBOLD(clrMAGENTA,"[ApplicationBarrierManager::handlePacket()]")
         << "In handlePacket.\n" << vprDEBUG_FLUSH;

   if ( NULL != packet.get() && NULL != node.get() )
   {
      switch ( packet->getPacketType() )
      {
      case cluster::Header::RIM_DATA_PACKET:
      {
         DataPacketPtr data_packet = boost::dynamic_pointer_cast<DataPacket>(packet);
         vprASSERT(NULL != data_packet.get() && "Dynamic cast failed!");

         // Find the ApplicationBarrier Object that we have received data
         // for.
         ApplicationBarrier* barrier =
            getApplicationBarrier(data_packet->getObjectId());

         if (barrier != NULL)
         {
            // Parse the object's data using the temporary ObjectReader
            barrier->incWaitingNodes();
         }
         else
         {
            vprDEBUG(gadgetDBG_RIM,vprDBG_WARNING_LVL)
               << clrOutBOLD(clrCYAN,"[ApplicationBarrierManager] ")
               << "Got data for an unknown ApplicationBarrier object: "
               << data_packet->getObjectId() << std::endl << vprDEBUG_FLUSH;
         }
         break;
      }
      default:
         vprDEBUG(gadgetDBG_RIM,vprDBG_WARNING_LVL)
            << clrOutBOLD(clrCYAN,"[ApplicationBarrierManager] ")
            << "Don't know how to handle a packet of type: "
            << packet->getPacketType() << std::endl << vprDEBUG_FLUSH;
         break;
      }
   }
}
Ejemplo n.º 30
0
//--------------------------------------
bool CGameServer::OnTcpDispatch(const PacketPtr& PktPtr, PTCP_PARAM pTcp)
{
	// PTCP_PARAM->pCache == nullptr, 上层可以保存从底层申请的缓存数据
	// PTCP_PARAM->pCache, PTCP_PARAM->index是底层申请的缓存数据的起始地址和索引号
	// 如果上层保存缓存, 设置PTCP_PARAM->pData为nullptr通知网络底层
	// 释放缓存使用MObject::sMCFree(index, pCache)
	bool bRet = false;
	if (PktPtr->GetEvent() != PAK_EVENT_LIVE) {
		switch (PktPtr->GetType()) {
		case PAK_TYPE_GATE:
			{
				bRet = DispatchGateServer(PktPtr, pTcp->krSocket);
			}
			break;
		case PAK_TYPE_ZONE:
			{
				bRet = DispatchZoneServer(PktPtr, pTcp->krSocket);
			}
			break;
		case PAK_TYPE_GAMEDB:
			{
				bRet = DispatchGameDBServer(PktPtr, pTcp->krSocket);
			}
			break;
		case PAK_TYPE_CENTER:
			{
				bRet = DispatchCenterServer(PktPtr, pTcp->krSocket);
			}
			break;
		default:
			{
				LOGV_WARN(m_FileLog, TF("[游戏服务器]%p信令包服务器类型[%d]不正确"), pTcp->krSocket, PktPtr->GetType());
				bRet = false;
			}
		}
	}
	else {
		CPAKSimple<PAK_EVENT_LIVEACK, PAK_TYPE_GAME> LiveAck;
		LiveAck.AdjustSize();
		bRet = m_NetworkPtr->Send(pTcp->krSocket, LiveAck);
	}
	return bRet;
}