Example #1
0
void GUIApplication::consoleConnect(const std::vector<String>& params, String& output)
{
    if (!m_userCreated)
    {
        output = "\nThis command is only available after log-in";
        return;
    }
    if (params.size() < 3)
    {
        output = "\nExpected more parameters: connect <address> <tcp_port>";
        return;
    }

    unsigned int tcpPort = 0;
    try {
        tcpPort = boost::lexical_cast<unsigned int>(params[2]);
    }
    catch (boost::bad_lexical_cast)
    {
        output = "\nBad parameter types. Expected: connect <address> <tcp_port>";
        return;
    }

    NetConnection* newConnection = new NetConnection(*m_networkService);
    RemoteMessagePeer* myPeer = new RemoteMessagePeer(newConnection, false, *m_networkService);

    newConnection->connectTo(params[1].c_str(), tcpPort);
    if (!m_networkThread.isRunning())
        m_networkThread.start();
    output = "\ncommand accepted.";
}
Example #2
0
void UpdateWindowTitle(char* iNewTitle) {
#ifdef WIN32
	char tmp[500];
	if (iNewTitle) {
		snprintf(tmp, sizeof(tmp), "%i: %s", net.GetZonePort(), iNewTitle);
	}
	else {
		if (zone) {
			#if defined(GOTFRAGS) || defined(_DEBUG)
				snprintf(tmp, sizeof(tmp), "%i: %s, %i clients, %i", net.GetZonePort(), zone->GetShortName(), numclients, getpid());
			#else
				snprintf(tmp, sizeof(tmp), "%i: %s, %i clients", net.GetZonePort(), zone->GetShortName(), numclients);
			#endif
		}
		else {
			#if defined(GOTFRAGS) || defined(_DEBUG)
				snprintf(tmp, sizeof(tmp), "%i: sleeping, %i", net.GetZonePort(), getpid());
			#else
				snprintf(tmp, sizeof(tmp), "%i: sleeping", net.GetZonePort());
			#endif
		}
	}
	SetConsoleTitle(tmp);
#endif
}
Example #3
0
bool GUIApplication::onJoinServerClicked(const CEGUI::EventArgs&)
{
    String playerName = m_guiContext->getRootWindow()->getChild("JoinServer/playerName")->getText();
    String serverIp = m_guiContext->getRootWindow()->getChild("JoinServer/serverIp")->getText();

    m_userName = playerName;
    m_userListensUdpPort = 11223;
    m_userCreated = true;

    RemotePeersManager::getManager()->setMyName(m_userName.c_str());
    RemotePeersManager::getManager()->setMyUdpPort(m_userListensUdpPort);
    // TODO: start listening at given UDP port.
    std::string errStr;
    if (!m_networkThread.startUdpListener(m_userListensUdpPort, errStr))
    {
        return true;
    }

    NetConnection* newConnection = new NetConnection(*m_networkService);
    RemoteMessagePeer* myPeer = new RemoteMessagePeer(newConnection, false, *m_networkService);

    newConnection->connectTo(serverIp.c_str(), 1778);
    if (!m_networkThread.isRunning())
        m_networkThread.start();

    return true;
}
Example #4
0
void AckCallback(net_sender_t& from, NetMessage* msg) {
	DevConsole::ConsolePrintf("%s", RGBA(0, 0, 255, 255), "Received ack");


	NetConnection* connection = from.connection;
	if (connection == nullptr) {
		return;
	}

	size_t byteAt = 0;
	unsigned char* messageData = msg->GetBuffer();

	uint8_t numAcks = *(uint8_t*)(messageData + byteAt);
	byteAt += sizeof(uint8_t);

	for (int ack = 0; ack < numAcks; ack++) {
		uint16_t ackID = *(uint16_t*)(messageData + byteAt);
		byteAt += sizeof(uint16_t);

		ReliableTracker *tracker = connection->FindAndRemoveTracker(ackID);
		if (tracker != nullptr) {
			for (uint16_t reliable_id : tracker->m_reliableIDs) {
				connection->MarkReliableAsReceived(reliable_id);
			}
		}
	}
}
Example #5
0
void NetInterface::handleDisconnect(const Address &address, BitStream *stream)
{
   NetConnection *conn = findConnection(address);
   if(!conn)
      return;

   ConnectionParameters &theParams = conn->getConnectionParameters();

   Nonce nonce, serverNonce;
   char reason[256];

   nonce.read(stream);
   serverNonce.read(stream);

   if(nonce != theParams.mNonce || serverNonce != theParams.mServerNonce)
      return;

   U32 decryptPos = stream->getBytePosition();
   stream->setBytePosition(decryptPos);

   if(theParams.mUsingCrypto)
   {
      SymmetricCipher theCipher(theParams.mSharedSecret);
      if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher))
         return;
   }
   stream->readString(reason);

   conn->setConnectionState(NetConnection::Disconnected);
   conn->onConnectionTerminated(NetConnection::ReasonRemoteDisconnectPacket, reason);
   removeConnection(conn);
}
NetConnection *NetConnection::lookup(const NetAddress *addr)
{
   U32 hashIndex = HashNetAddress(addr);
   for(NetConnection *walk = mHashTable[hashIndex]; walk; walk = walk->mNextTableHash)
      if(Net::compareAddresses(addr, walk->getNetAddress()))
         return walk;
   return NULL;
}
void ICACHE_FLASH_ATTR esp8266_connectCallback(void* arg)
{
    uart0_tx_buffer("connected\r\n", 11);
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;

    netConn->connectCallback(netConn->userData, net_ok);
}
Example #8
0
VTorque::SoundSourceType *VTorque::playSound( SoundEffectType *pSoundProfile, SceneObjectType *pObject, const U32 &pPosition, const F32 &pPitch )
{
    if ( !pSoundProfile )
    {
        // Sanity!
        return NULL;
    }

#ifdef VT_EDITOR

    // Fetch Reference Transform.
    const MatrixF &transform = pObject->getTransform();

    // Play Sound.
    SFXSound *source = ( SFXSound* )SFX->playOnce( pSoundProfile, &transform );

    if ( source )
    {
        // Set Position.
        source->setPosition( pPosition );

        // Set Pitch.
        source->setPitch( pPitch );
    }

    // Return Source.
    return source;

#else

    // Fetch Client Group.
    SimGroup* clientGroup = Sim::getClientGroup();

    for ( SimGroup::iterator itr = clientGroup->begin(); itr != clientGroup->end(); itr++ )
    {
        NetConnection *connection = static_cast<NetConnection*>( *itr );
        if ( connection )
        {
            // Create Event.
            VSoundEffectNetEvent *event = new VSoundEffectNetEvent();

            // Setup Event.
            event->mProfile   = pSoundProfile;
            event->mPosition  = pPosition;
            event->mPitch     = pPitch;
            event->mIs3D      = true;
            event->mTransform = pObject->getTransform();

            // Post Event.
            connection->postNetEvent( event );
        }
    }

    return NULL;

#endif
}
void ICACHE_FLASH_ATTR esp8266_disconnectCallback(void* arg)
{
    uart0_tx_buffer("disconnected\r\n", 14);
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;

    esp8266_destroyConnection(netConn);
    netConn->disconnectCallback(netConn->userData, net_ok);
}
void ICACHE_FLASH_ATTR esp8266_resolveCallback(const char* name, ip_addr_t* ip, void* arg)
{
    
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;
    uart0_tx_buffer("get conn\r\n", 10);
    HTTPESP8266ConnectionData* driver = esp8266_getConnection(netConn);

    uart0_tx_buffer("check ip\r\n", 10);
    if(!ip)
    { // failed to lookup the hostname
        uart0_tx_buffer("bad ip\r\n", 8);
        esp8266_destroyConnection(netConn);
        netConn->readCallback(netConn->userData, NULL, 0, net_error);
        return;
    }

    char pageBuffer[20];
    ets_sprintf(pageBuffer, "r: %d.%d.%d.%d\r\n", IP2STR(ip));
    uart0_tx_buffer(pageBuffer, strlen(pageBuffer));

    uart0_tx_buffer("set tcp callbacks\r\n", 19);
    espconn_regist_connectcb(conn, esp8266_connectCallback);
    espconn_regist_disconcb(conn, esp8266_disconnectCallback);
    espconn_regist_reconcb(conn, esp8266_reconnectCallback);
    uart0_tx_buffer("set callbacks\r\n", 15);
    espconn_regist_recvcb(conn, esp8266_recvCallback);
    espconn_regist_sentcb(conn, esp8266_sendCallback);

    uart0_tx_buffer("set ip\r\n", 8);
    ets_memcpy(&conn->proto.tcp->remote_ip, ip, 4);
    if(driver->secure)
    {
        uart0_tx_buffer("async sconnect\r\n", 16);
        conn->proto.tcp->remote_port = 443;
        
        ets_sprintf(pageBuffer, "port: %d\r\n", conn->proto.tcp->remote_port);
        uart0_tx_buffer(pageBuffer, strlen(pageBuffer));

        sint8 r = espconn_secure_connect(conn);
        ets_sprintf(pageBuffer, "c_conn: %d\r\n", r);
        uart0_tx_buffer(pageBuffer, strlen(pageBuffer));
    }
    else
    {
        uart0_tx_buffer("async connect\r\n", 15);
        conn->proto.tcp->remote_port = 80;
        
        ets_sprintf(pageBuffer, "port: %d\r\n", conn->proto.tcp->remote_port);
        uart0_tx_buffer(pageBuffer, strlen(pageBuffer));

        sint8 r = espconn_connect(conn);
        ets_sprintf(pageBuffer, "c_conn: %d\r\n", r);
        uart0_tx_buffer(pageBuffer, strlen(pageBuffer));
    }
}
void ICACHE_FLASH_ATTR esp8266_recvCallback(void* arg, char* buffer, unsigned short size)
{
    char pageBuffer[20];
    ets_sprintf(pageBuffer, "rx: %d\r\n", size);
    uart0_tx_buffer(pageBuffer, strlen(pageBuffer));
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;

    netConn->readCallback(netConn->userData, buffer, size, net_ok);
}
void ICACHE_FLASH_ATTR esp8266_reconnectCallback(void* arg, sint8 err)
{
    char pageBuffer[20];
    ets_sprintf(pageBuffer, "recon: %d\r\n", err);
    uart0_tx_buffer(pageBuffer, strlen(pageBuffer));
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;

    esp8266_destroyConnection(netConn);
    netConn->readCallback(netConn->userData, NULL, 0, net_error);
}
Example #13
0
void VTorque::setPostEffectOn( PostEffectType *pPostEffect, const bool &pStatus )
{
    if ( !pPostEffect )
    {
        // Sanity!
        return;
    }

#ifdef VT_EDITOR

    if ( pStatus )
    {
        // Enable Effect.
        pPostEffect->enable();
    }
    else
    {
        // Disable Effect.
        pPostEffect->disable();
    }

#else

    // Fetch Name.
    StringTableEntry name = pPostEffect->getName();
    if ( !name || name == StringTable->insert( "" ) )
    {
        Con::warnf( "VTorque::setPostEffectOn() - Invalid Object Name." );
        return;
    }

    // Fetch Client Group.
    SimGroup* clientGroup = Sim::getClientGroup();

    for ( SimGroup::iterator itr = clientGroup->begin(); itr != clientGroup->end(); itr++ )
    {
        NetConnection *connection = static_cast<NetConnection*>( *itr );
        if ( connection )
        {
            // Create Event.
            VPostEffectNetEvent *event = new VPostEffectNetEvent();

            // Setup Event.
            event->mPostEffect = name;
            event->mEnabled    = pStatus;

            // Post Event.
            connection->postNetEvent( event );
        }
    }

#endif
}
Example #14
0
//--------------------------------------------------------------------------
// OnAdd
//--------------------------------------------------------------------------
bool Splash::onAdd()
{
   // first check if we have a server connection, if we dont then this is on the server
   //  and we should exit, then check if the parent fails to add the object
   NetConnection* conn = NetConnection::getConnectionToServer();
   if(!conn || !Parent::onAdd())
      return false;

   if( !mDataBlock )
   {
      Con::errorf("Splash::onAdd - Fail - No datablock");
      return false;
   }

   mDelayMS = mDataBlock->delayMS + sgRandom.randI( -mDataBlock->delayVariance, mDataBlock->delayVariance );
   mEndingMS = mDataBlock->lifetimeMS + sgRandom.randI( -mDataBlock->lifetimeVariance, mDataBlock->lifetimeVariance );

   mVelocity = mDataBlock->velocity;
   mHeight = mDataBlock->height;
   mTimeSinceLastRing = 1.0 / mDataBlock->ejectionFreq;

   for( U32 i=0; i<SplashData::NUM_EMITTERS; i++ )
   {
      if( mDataBlock->emitterList[i] != NULL )
      {
         ParticleEmitter * pEmitter = new ParticleEmitter;
         pEmitter->onNewDataBlock( mDataBlock->emitterList[i], false );
         if( !pEmitter->registerObject() )
         {
            Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
            delete pEmitter;
            pEmitter = NULL;
         }
         mEmitterList[i] = pEmitter;
      }
   }

   spawnExplosion();

   mObjBox.minExtents = Point3F( -1, -1, -1 );
   mObjBox.maxExtents = Point3F(  1,  1,  1 );
   resetWorldBox();

   gClientSceneGraph->addObjectToScene(this);

   removeFromProcessList();
   ClientProcessList::get()->addObject(this);

   conn->addObject(this);

   return true;
}
Example #15
0
void NetJoinRequestCallback(NetSender* sender, NetMessage& msg) {
	//do nothing
	ConsolePrintString("\nNetJoinRequestCallback => ");

	BinaryBufferParser bp(&msg.messageBuffer[0], msg.curSize);
	std::string otherName = bp.ReadNextString();
	ConsolePrintString(otherName);

	if (NetworkSystem::s_gameSession->CanAddNewConn()) {
		Byte nextConnIndex = NetworkSystem::s_gameSession->GetNextJoinableConnIndex();
		NetworkSystem::s_gameSession->AddConnection(*sender->addr, 0xff, "client_"+ShortToString(nextConnIndex)+"(O.o)((_ | __ | _");

		//sender->conn = NetworkSystem::s_gameSession->FindConnectionInMap(nextConnIndex);
		NetConnection* newClientConnPtr = NetworkSystem::s_gameSession->FindConnectionInMap(0xff);
		if (newClientConnPtr) {
			NetMessage* joinAcceptMsg = new NetMessage(EN_MSG_ID_JOIN_ACCEPT);
			Byte myMaxConns = NetworkSystem::s_gameSession->GetMaxConnections();
			joinAcceptMsg->WRITE_BYTES(myMaxConns);
			joinAcceptMsg->WRITE_BYTES(nextConnIndex);

			if (NetworkSystem::s_gameSession->m_connSelf) {

				Byte myConnIndex = NetworkSystem::s_gameSession->m_connSelf->GetConnIndex();

				joinAcceptMsg->WRITE_BYTES(myConnIndex);
				//joinAcceptMsg->WriteMessageData(&myConnIndex, SIZE_OF(myConnIndex));

				//joinAcceptMsg->WriteMessageData(&std::string(AllocLocalHostName() + "__(O.o)((_|__|_\0"), SIZE_OF(std::string));
				std::string hostNameString = AllocLocalHostName();
				joinAcceptMsg->WRITE_BYTES(hostNameString);

			}//end of if my info exists

			//doing sender->conn causes system to spam new conns

			newClientConnPtr->SendNetMessage(*joinAcceptMsg);

			//newClientConnPtr->SetConnIndex(0xff);

			newClientConnPtr->SetName("client_" + ShortToString(nextConnIndex) + "(O.o)((_ | __ | _");
		}
		
	}
	else {
		NetMessage* joinDenyMsg = new NetMessage(EN_MSG_ID_JOIN_DENY);

		NetworkSystem::s_gameSession->SendNetMessage(*joinDenyMsg);
	}
	

}
bool NetworkSession::RemoveConnection(const NetAddress&addr, const Byte& connIndex) {
	NetConnectionMapIterator it = m_netConnectionMap.find(GetNetConnectionMapKey(addr, connIndex));
	if (it != m_netConnectionMap.end()) {
		NetConnection* connection = it->second;
		if (connection) {
			connection->CleanupTrackers();
			delete connection;
			connection = NULL;
		}
		it = m_netConnectionMap.erase(it);
		return true;
	}
	return false;
}
Example #17
0
void NetInterface::handleConnectReject(const NetAddress *address, BitStream *stream)
{
   U32 connectSequence;
   stream->read(&connectSequence);
   NetConnection *conn = findPendingConnection(address, connectSequence);
   if(!conn || (conn->getConnectionState() != NetConnection::AwaitingChallengeResponse &&
                conn->getConnectionState() != NetConnection::AwaitingConnectResponse))
      return;
   removePendingConnection(conn);
   char reason[256];
   stream->readString(reason);
   conn->onConnectionRejected(reason);
   conn->deleteObject();
}
void ICACHE_FLASH_ATTR esp8266_sendCallback(void* arg)
{
    uart0_tx_buffer("tx\r\n", 4);
    struct espconn* conn = (struct espconn*)arg;
    NetConnection* netConn = (NetConnection*)conn->reverse;
    HTTPESP8266ConnectionData* driver = esp8266_getConnection(netConn);

    if(driver->writeDataSize > 0)
    {
        net_asyncWrite(netConn, driver->writeData, driver->writeDataSize);
    }
    else
    {
        netConn->writeCallback(netConn->userData, net_ok);
    }
}
Example #19
0
void WorldServer::SetConnectInfo()
{
	ServerPacket* pack = new ServerPacket(ServerOP_SetConnectInfo, sizeof(ServerConnectInfo));


	pack->pBuffer = new uchar[pack->size];
	memset(pack->pBuffer, 0, pack->size);

	ServerConnectInfo* sci = (ServerConnectInfo*) pack->pBuffer;
	sci->port = net.GetZonePort();
	strcpy(sci->address, net.GetZoneAddress());

	SendPacket(pack);

	safe_delete(pack);//delete pack;
}
Example #20
0
void Lightning::warningFlashes()
{
   AssertFatal(isServerObject(), "Error, client objects may not initiate lightning!");


   SimGroup* pClientGroup = Sim::getClientGroup();
   for (SimGroup::iterator itr = pClientGroup->begin(); itr != pClientGroup->end(); itr++) {
      NetConnection* nc = static_cast<NetConnection*>(*itr);
      if (nc != NULL)
      {
         LightningStrikeEvent* pEvent = new LightningStrikeEvent;
         pEvent->mLightning = this;

         nc->postNetEvent(pEvent);
      }
   }
}
Example #21
0
void NetInterface::removeConnection(NetConnection *conn)
{
   for(S32 i = 0; i < mConnectionList.size(); i++)
   {
      if(mConnectionList[i] == conn)
      {
         mConnectionList.erase_fast(i);
         break;
      }
   }
   U32 index = conn->getNetAddress().hash() % mConnectionHashTable.size();
   U32 startIndex = index;

   while(mConnectionHashTable[index] != conn)
   {
      index++;
      if(index >= (U32) mConnectionHashTable.size())
         index = 0;
      TNLAssert(index != startIndex, "Attempting to remove a connection that is not in the table.") // not in the table
      if(index == startIndex)
         return;
   }
   mConnectionHashTable[index] = NULL;

   // rehash all subsequent entries until we find a NULL entry:
   for(;;)
   {
      index++;
      if(index >= (U32) mConnectionHashTable.size())
         index = 0;
      if(!mConnectionHashTable[index])
         break;
      NetConnection *rehashConn = mConnectionHashTable[index];
      mConnectionHashTable[index] = NULL;
      U32 realIndex = rehashConn->getNetAddress().hash() % mConnectionHashTable.size();
      while(mConnectionHashTable[realIndex] != NULL)
      {
         realIndex++;
         if(realIndex >= (U32) mConnectionHashTable.size())
            realIndex = 0;
      }
      mConnectionHashTable[realIndex] = rehashConn;
   }
   conn->decRef();
}
Example #22
0
void NetClient::Disconnect()
{
	DeleteModels(true);

	NetConnection* connection = _connection;
	_connection = NULL;

	//lsl::SafeDelete(connection);

	if (connection)
	{
		connection->Close();
		_net->ReleaseConnection(connection);
	}
	connection = NULL;

	channel()->Unbind();
}
Example #23
0
void NetInterface::handleDisconnect(const NetAddress *address, BitStream *stream)
{
   NetConnection *conn = NetConnection::lookup(address);
   if(!conn)
      return;

   U32 connectSequence;
   char reason[256];

   stream->read(&connectSequence);
   stream->readString(reason);

   if(conn->getSequence() != connectSequence)
      return;

   conn->onDisconnect(reason);
   conn->deleteObject();
}
Example #24
0
void NetInterface::handleConnectChallengeResponse(const Address &address, BitStream *stream)
{
   NetConnection *conn = findPendingConnection(address);
   if(!conn || conn->getConnectionState() != NetConnection::AwaitingChallengeResponse)
      return;
   
   Nonce theNonce;
   theNonce.read(stream);

   ConnectionParameters &theParams = conn->getConnectionParameters();
   if(theNonce != theParams.mNonce)
      return;

   stream->read(&theParams.mClientIdentity);

   // see if the server wants us to solve a client puzzle
   theParams.mServerNonce.read(stream);
   stream->read(&theParams.mPuzzleDifficulty);

   if(theParams.mPuzzleDifficulty > ClientPuzzleManager::MaxPuzzleDifficulty)
      return;

   // see if the connection needs to be authenticated or uses key exchange
   if(stream->readFlag())
   {
      if(stream->readFlag())
      {
         theParams.mCertificate = new Certificate(stream);
         if(!theParams.mCertificate->isValid() || !conn->validateCertficate(theParams.mCertificate, true))
            return;         
         theParams.mPublicKey = theParams.mCertificate->getPublicKey();
      }
      else
      {
         theParams.mPublicKey = new AsymmetricKey(stream);
         if(!theParams.mPublicKey->isValid() || !conn->validatePublicKey(theParams.mPublicKey, true))
            return;
      }
      if(mPrivateKey.isNull() || mPrivateKey->getKeySize() != theParams.mPublicKey->getKeySize())
      {
         // we don't have a private key, so generate one for this connection
         theParams.mPrivateKey = new AsymmetricKey(theParams.mPublicKey->getKeySize());
      }
      else
         theParams.mPrivateKey = mPrivateKey;
      theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey);
      //logprintf("shared secret (client) %s", theParams.mSharedSecret->encodeBase64()->getBuffer());
      Random::read(theParams.mSymmetricKey, SymmetricCipher::KeySize);
      theParams.mUsingCrypto = true;
   }

   TNLLogMessageV(LogNetInterface, ("Received Challenge Response: %8x", theParams.mClientIdentity ));

   conn->setConnectionState(NetConnection::ComputingPuzzleSolution);
   conn->mConnectSendCount = 0;

   theParams.mPuzzleSolution = 0;
   conn->mConnectLastSendTime = getCurrentTime();
   continuePuzzleSolution(conn);   
}
void NetInterface::handleConnectAccept(const Address &address, BitStream *stream)
{
   Nonce nonce, serverNonce;

   nonce.read(stream);
   serverNonce.read(stream);

   U32 decryptPos = stream->getBytePosition();
   stream->setBytePosition(decryptPos);

   // Make sure we're actually waiting for a connection.  If not, then there's something wrong, and we bail.
   NetConnection *conn = findPendingConnection(address);
   if(!conn || conn->getConnectionState() != NetConnection::AwaitingConnectResponse)
      return;

   ConnectionParameters &theParams = conn->getConnectionParameters();

   if(theParams.mNonce != nonce || theParams.mServerNonce != serverNonce)
      return;

   if(theParams.mUsingCrypto)
   {
      SymmetricCipher theCipher(theParams.mSharedSecret);
      if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher))
         return;
   }
   U32 recvSequence;
   stream->read(&recvSequence);
   conn->setInitialRecvSequence(recvSequence);

   NetConnection::TerminationReason reason;
   if(!conn->readConnectAccept(stream, reason))
   {
      removePendingConnection(conn);
      return;
   }

   if(theParams.mUsingCrypto)
   {
      stream->read(SymmetricCipher::KeySize, theParams.mInitVector);
      conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector));
   }

   addConnection(conn);           // First, add it as a regular connection,
   removePendingConnection(conn); // then remove it from the pending connection list

   conn->setConnectionState(NetConnection::Connected);
   conn->onConnectionEstablished(); // notify the connection that it has been established
   logprintf(LogConsumer::LogNetInterface, "Received Connect Accept - connection established.");
}
Example #26
0
static void _scopeCallback( SceneObject* object, void* data )
{
   if( !object->isScopeable() )
      return;

   ScopingInfo* info = reinterpret_cast< ScopingInfo* >( data );
   NetConnection* connection = info->connection;

   F32 difSq = ( object->getWorldSphere().center - info->scopePoint ).lenSquared();
   if( difSq < info->scopeDistSquared )
   {
      // Not even close, it's in...
      connection->objectInScope( object );
   }
   else
   {
      // Check a little more closely...
      F32 realDif = mSqrt( difSq );
      if( realDif - object->getWorldSphere().radius < info->scopeDist)
         connection->objectInScope( object );
   }
}
Example #27
0
void NetInterface::handleConnectChallengeResponse(const NetAddress *address, BitStream *stream)
{
   Con::printf("Got Connect challenge Response");
   U32 connectSequence;
   stream->read(&connectSequence);

   NetConnection *conn = findPendingConnection(address, connectSequence);
   if(!conn || conn->getConnectionState() != NetConnection::AwaitingChallengeResponse)
      return;

   U32 addressDigest[4];
   stream->read(&addressDigest[0]);
   stream->read(&addressDigest[1]);
   stream->read(&addressDigest[2]);
   stream->read(&addressDigest[3]);
   conn->setAddressDigest(addressDigest);

   conn->setConnectionState(NetConnection::AwaitingConnectResponse);
   conn->mConnectSendCount = 0;
   Con::printf("Sending Connect Request");
   sendConnectRequest(conn);
}
Example #28
0
/*
 *  初始化
 */
bool LoginLayer::init() {
    if (!CCLayer::init()) {
        return false;
    }
    
    NetConnection* pNetConnection = NetConnection::getInstance();
    pNetConnection->setHandleNetDataDelegate(this);
    
    unsigned int server_id = CCUserDefault::sharedUserDefault()->getIntegerForKey(LOGIN_SERVER_KEY, 0);
    /* 更改服务器名 */
    if (0 == server_id) {
        pNetConnection->setUUU(HTTP_SERVER_URL); /* 默认新浪服务器 */
        m_pGameState->setServerId(0);
    } else {
        pNetConnection->setUUU(HTTP_SERVER_URL1); /* 研发服务器 */
        m_pGameState->setServerId(1);
    }
    /* 初始化UI组件 */
    _initComponent();
    
    return true;
}
Example #29
0
void GuoZhanLayer::_onBtnSelected(int idx) {
    unsigned int cityId = 0;
    switch (idx) {
        case 1:
        {
            cityId = 1;
            m_pBattle->setSelectCity(1);
        }
            break;
        case 2:
        {
            cityId = 2;
            m_pBattle->setSelectCity(2);
        }
            break;
        case 3:
        {
            cityId = 3;
            m_pBattle->setSelectCity(3);
        }
            break;
        default:
            break;
    }
    
    if (cityId > 0) {
        NetConnection* pNetConnection = NetConnection::getInstance();
        char szPostBuffer[MAX_POSTTO_SERVER_BUFFER_SIZE];
        memset(szPostBuffer, '\0', MAX_POSTTO_SERVER_BUFFER_SIZE);
        
        sprintf(szPostBuffer, "c=cwar&a=city&city=%d&uid=%s", cityId,
                GamePlayer::getInstance()->getUid().c_str());
        char szHttpTag[] = HTTP_REQUEST_ENTERCITY_TAG;
        CCLog("post 进入城池 = %s", szPostBuffer);
        pNetConnection->commitPostRequestData(szPostBuffer, szHttpTag);
    }
}
Example #30
0
void NetInterface::handleConnectAccept(const Address &address, BitStream *stream)
{
   Nonce nonce, serverNonce;

   nonce.read(stream);
   serverNonce.read(stream);
   U32 decryptPos = stream->getBytePosition();
   stream->setBytePosition(decryptPos);

   NetConnection *conn = findPendingConnection(address);
   if(!conn || conn->getConnectionState() != NetConnection::AwaitingConnectResponse)
      return;

   ConnectionParameters &theParams = conn->getConnectionParameters();

   if(theParams.mNonce != nonce || theParams.mServerNonce != serverNonce)
      return;

   if(theParams.mUsingCrypto)
   {
      SymmetricCipher theCipher(theParams.mSharedSecret);
      if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher))
         return;
   }
   U32 recvSequence;
   stream->read(&recvSequence);
   conn->setInitialRecvSequence(recvSequence);

   const char *errorString = NULL;
   if(!conn->readConnectAccept(stream, &errorString))
   {
      removePendingConnection(conn);
      return;
   }
   if(theParams.mUsingCrypto)
   {
      stream->read(SymmetricCipher::KeySize, theParams.mInitVector);
      conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector));
   }

   addConnection(conn); // first, add it as a regular connection
   removePendingConnection(conn); // remove from the pending connection list

   conn->setConnectionState(NetConnection::Connected);
   conn->onConnectionEstablished(); // notify the connection that it has been established
   TNLLogMessageV(LogNetInterface, ("Received Connect Accept - connection established."));
}