Beispiel #1
0
void CMyTcpServer::incomingConnection( int socketDescriptor )
{
    // client endpoint / connectToHost
    CPeerSocket* pSocket = new CPeerSocket( this );
    pSocket->setSocketDescriptor( socketDescriptor );
    //addPendingConnection( pSocket );
    connect( pSocket, SIGNAL( disconnected( ) ), this, SLOT( HandleDisconnect( ) ) );

    if ( GetMgmtTCPFlag( ) ) {
        connect( pSocket, SIGNAL( readyRead( ) ), this, SLOT( GetMgmtStream( ) ) );
    } else {
        connect( pSocket, SIGNAL( readyRead( ) ), this, SLOT( GetStream( ) ) );
    }

    connect( pSocket, SIGNAL( error( QAbstractSocket::SocketError ) ),
             this, SLOT( TcpError( QAbstractSocket::SocketError ) ) );

    QString strKey;
    QString strMsg;
    GetKeyMsg( pSocket, strKey, strMsg, true );

    clientHash.insert( strKey, pSocket );

    emit NotifyMessage( strMsg );
}
Beispiel #2
0
quint64 CTcpClient::SendData( const QByteArray & byteArray )
{
    HandleDisconnect( );
    quint64 nRet = 0;

    int nPackageSize = 10 * 1024 * 1024;
    int nTotalSize = byteArray.count( );
    int nMode = nTotalSize / nPackageSize;
    int nSurplus = nTotalSize % nPackageSize;
    const char* pData = byteArray.data( );
    const char* pPkgData = NULL;

    if ( 0 == nMode ) { // < 10M
        nRet += write( byteArray );
    } else { // >= 10M
        int nIndex = 0;
        for ( nIndex = 0; nIndex < nMode; nIndex++ ) {
            pPkgData = ( pData + nIndex * nPackageSize );
            nRet += write( pPkgData, nPackageSize );
        }

        if ( 0 != nSurplus ) {
            pPkgData = ( pData + nIndex * nPackageSize );
            nRet += write( pPkgData, nSurplus );
        }
    }

    if ( !flush( ) ) {
        waitForBytesWritten( );
    }

    return nRet;
}
Beispiel #3
0
void CTcpClient::TcpError( QAbstractSocket::SocketError socketError )
{
    QString strMsg;
    CNetCommFunction::GetErrorMsg( strMsg, socketError, this );
    strMsg = "Tcp socket :\r\n" + strMsg;
    emit NotifyMessage( strMsg );

    HandleDisconnect( );
}
Beispiel #4
0
CTcpClient::CTcpClient(QObject *parent) :
    QTcpSocket(parent)
{
    pData = NULL;
    Clear( );
    pData = new QByteArray( );

    pTextCodec = NULL;
    connect( this, SIGNAL( disconnected( ) ), this, SLOT( HandleDisconnect( ) ) );
    connect( this, SIGNAL( error( QAbstractSocket::SocketError ) ),
                  this, SLOT( TcpError( QAbstractSocket::SocketError ) ) );
}
Beispiel #5
0
  TcpEdge::TcpEdge(const Address &local, const Address &remote, bool outgoing,
      QTcpSocket *socket) :
    Edge(local, remote, outgoing),
    _socket(socket, &QObject::deleteLater)
  {
    socket->setParent(0);

    socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(Read()));
    QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(HandleDisconnect()));
    QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
        this, SLOT(HandleError(QAbstractSocket::SocketError)));
  }
  void ConnectionManager::CreateConnection(const QSharedPointer<Edge> &pedge,
      const Id &rem_id)
  {
    QSharedPointer<Connection> con(new Connection(pedge, _local_id, rem_id),
        &QObject::deleteLater);
    con->SetSharedPointer(con);
    _con_tab.AddConnection(con);
    qDebug() << "Handle new connection:" << con->ToString();

    QObject::connect(con.data(), SIGNAL(CalledDisconnect()),
        this, SLOT(HandleDisconnect()));

    QObject::connect(con.data(), SIGNAL(Disconnected(const QString &)),
        this, SLOT(HandleDisconnected(const QString &)));

    emit NewConnection(con);
  }
Beispiel #7
0
bool NetServer::ServerStep()
{
	// use lastTic to keep track of how many tics per second we have; control "tics per second"
	// perform any periodic, timed events here

	ENetEvent event;
	int status = enet_host_service(server, &event, HOST_TIMEOUT);

	if (status < 0) return false; // ERROR happened! Server shut down!	

	TimedEvent();

	if (status == 0) return true; // nothing to do, try again later

	switch(event.type)
	{
	case ENET_EVENT_TYPE_CONNECT:
		{
			printf ("A new client (%d) connected from %x:%u.\n", 
				event.peer,
				event.peer -> address.host,
				event.peer -> address.port);

			client *c = new client;
			char hostname[256] = "error";
			enet_address_get_host_ip(&event.peer->address, hostname, 256);
			printf("%s connected\n", hostname);

			if (event.peer != master)
			{
				c->hostname = string(hostname);
				c->peer = event.peer;
				c->state = ST_AUTH;

				// associate peer with the client object for them
				event.peer->data = c;

				// Call HandleConnect method of the game logic
				// if it returns false, then that means connection denied, otherwise specifies state client is in
				// also add to list of clients
				if (HandleConnect(event.peer)) {
					bool client_added = false;
					for (size_t i = 0; i < clients.size(); i++) {
						if (clients.at(i)->state == ST_EMPTY) {
							clients.at(i) = c;
							client_added = true;
							break;
						}
					}
					if (!client_added)
						clients.push_back(c);
				} else {
					enet_peer_disconnect(event.peer, 121);
				}
			} else {
				MasterCheckin();
			}
			break;
		}

	case ENET_EVENT_TYPE_DISCONNECT:
		{
			if (event.peer != master) {
				printf ("%d disconnected.\n", event.peer);

				// Call HandleDisconnect method some form of id for the connection
				HandleDisconnect(323, event.peer);

				// free up this client slot for reuse
				((client*) event.peer->data)->state = ST_EMPTY;
			} else {
				printf ("Master timed out.\n");
				master = 0;
			}
			break;
		}
	case ENET_EVENT_TYPE_RECEIVE:
		{
			char hostname[256] = "error";
			enet_address_get_host_ip(&event.peer->address, hostname, 256);
			printf("receiving packet.\n");
			printf ("A packet of length %u ",
				event.packet -> dataLength);
			printf("containing %s ",
				event.packet -> data);
			printf("was received from %s ",
				hostname);
			printf("on channel %u.\n",
				event.channelID);
			/*printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
			event.packet -> dataLength,
			event.packet -> data,
			((client*)event.peer -> data)->hostname.c_str(),
			event.channelID);*/

			client *c = (client*) event.peer->data;

			// Call Packet Handler to deal with packets, and send a response
			HandlePacket(event.packet->data, event.packet->dataLength, event.peer);

			if (event.packet->referenceCount == 0) enet_packet_destroy(event.packet);
			break;
		}
	default:
		break;
	}
	enet_host_flush(server);
	return true;
}
Beispiel #8
0
// Update
void _Server::Update(double FrameTime) {
	//if(std::abs(std::fmod(Time, 1.0)) >= 0.99)
	//	std::cout << "Server: O=" << ObjectManager->Objects.size() << " B=" << BattleManager->Objects.size() << std::endl;

	// Update network
	Network->Update(FrameTime);

	// Get events
	_NetworkEvent NetworkEvent;
	while(Network->GetNetworkEvent(NetworkEvent)) {

		switch(NetworkEvent.Type) {
			case _NetworkEvent::CONNECT:
				HandleConnect(NetworkEvent);
			break;
			case _NetworkEvent::DISCONNECT:
				HandleDisconnect(NetworkEvent);
			break;
			case _NetworkEvent::PACKET:
				HandlePacket(*NetworkEvent.Data, NetworkEvent.Peer);
				delete NetworkEvent.Data;
			break;
		}
	}

	// Update objects
	ObjectManager->Update(FrameTime);

	// Spawn battles
	for(auto &BattleEvent : BattleEvents)
		StartBattle(BattleEvent);

	BattleEvents.clear();

	// Update maps
	MapManager->Update(FrameTime);

	// Update battles
	BattleManager->Update(FrameTime);

	// Check if updates should be sent
	if(Network->NeedsUpdate()) {
		Network->ResetUpdateTimer();
		if(Network->GetPeers().size() > 0) {

			// Send object updates
			for(auto &Map : MapManager->Objects) {
				Map->SendObjectUpdates();
			}
		}
	}

	// Wait for peers to disconnect
	if(StartDisconnect) {
		Network->DisconnectAll();
		StartDisconnect = false;
		StartShutdown = true;
	}
	else if(StartShutdown && Network->GetPeers().size() == 0) {
		Done = true;
	}

	TimeSteps++;
	Time += FrameTime;

	// Update scripting environment
	Scripting->InjectTime(Time);

	// Update clock
	Clock += FrameTime * MAP_CLOCK_SPEED;
	if(Clock >= MAP_DAY_LENGTH)
		Clock -= MAP_DAY_LENGTH;

	// Update autosave
	SaveTime += FrameTime;
	if(SaveTime >= DEFAULT_AUTOSAVE_PERIOD) {
		SaveTime = 0;

		// Save players
		for(auto &Object : ObjectManager->Objects) {
			Save->SavePlayer(Object);
		}
	}
}
Beispiel #9
0
//////////////////////////////////////////////////////////////////////
// This is the high level download function for the Download Mode.
//
// Inputs: Fuses (platformsettings) and the TIM.
// Outputs: Returns a pointer to the next image which we will transfer
//          control to.
//
// It mainly determines the download mode (TIM or FBF) and calls the
// appropriate download routine.
//////////////////////////////////////////////////////////////////////
pIMAGE_INFO_3_4_0 DetermineModeAndDownload( pFUSE_SET pFuses, pTIM pTIM_h )
{
    pIMAGE_INFO_3_4_0 pBootImageInfo = NULL;
    FUNC_STATUS fs_Retval;
    volatile pProtocolISR pPortInterrupt;
    volatile pProtocolCmd pCommand;

	int start_time =0, cur_time=0;
	fs_Retval.ErrorCode = GeneralError;

	#if ZIMI_PB05
	int mTimeOut;

	extern UINT_T back_image_key;
	if(back_image_key)  //Onkey + reset
		mTimeOut =4;
	else
		mTimeOut =1;
	#endif
	
	InitDefaultPort( pFuses );
	//time_count_enable = 0;
    // The download port is opened. Get all the images and burn them to flash.
    // Start by trying to get a TIM followed by individual files.
    // If that fails, then try getting an FBF bundle.
    // If that fails as well, then treat this a a fatal error.
	start_time = GetOSCR0();
    do
    {
        pPortInterrupt = getProtocolISR();
		if(time_count_enable)
		{
			cur_time = GetOSCR0();
			if(OSCR0IntervalInSec(start_time, cur_time) >mTimeOut)  //xyl define
			{
				pBootImageInfo = NULL;
				goto shutdown;
			}
		}

		if (upload_times == 0)
		{
			goto disconnect; // no upload any more
		}

        if(pPortInterrupt->PreambleReceived == FALSE)
        {
        #if I2C
			resetTimer(); // reset charger 32s timer for key pressed download
		#endif
			fs_Retval.ErrorCode = SeqError;
            continue;
        }
		time_count_enable= 0;

		start_time = GetOSCR0();
		while (pPortInterrupt->CommandReceived == FALSE)
		{
			cur_time = GetOSCR0();
			if(OSCR0IntervalInSec(start_time, cur_time) > PROTOCOL_WAITTIME) //wait for command
			{
				pBootImageInfo = NULL;
				goto shutdown;
			}
		}

	    pCommand = getProtocolCmd();
	    switch(pCommand->Command)
	    {
	    case GetVersionCmd:
			// Used to differentiate from UPLOAD.
	        isDownload =  TRUE;
			#if I2C
			#if OLED_SUPPORT || LED_DISPLAY
			SoftwareUpgrade_Start();
			#endif
			#endif

	    	// Request the TIM first as originally implemented.
			// The new TIM is stored at pTIM_h->pConstTIM.

			// USB DMA can not access SQU, so OBM download DKB_NTIM to DDR, and then copy it to SQU
			// it will be fixed on Y0 board
	        fs_Retval = HandleRequest( DDR_DOWNLOAD_AREA_ADDR, TIMIDENTIFIER );
	        //fs_Retval = HandleRequest( (UINT_T)pTIM_h->pConsTIM, TIMIDENTIFIER );
	        if (fs_Retval.ErrorCode == NoError)
	        {
				// Before we call the TIM Download function which actually does the downloading,
				// copy the tim from its download location to its load address. 
				memcpy(pTIM_h->pConsTIM, DDR_DOWNLOAD_AREA_ADDR, 1024);

	            // pTIM_h is the newly downloaded TIM.
	            // It has a list of all the images that need to be downloaded and burned.
	            // The DownloadImages function will use DDR to hold the images while writing them to flash.
				pBootImageInfo = TIMDownloadMain( pTIM_h );
	        }
			else // download failed
			{
				FatalError(fs_Retval.ErrorCode);
			}
	        break;
			
	    case UploadDataHeaderCmd:
			// UPLOAD_DATA_AREA is in DDR
			// upload size limitted 0x1d00000 - 0x1000
	        fs_Retval = HandleRequest( (UINT_T)UPLOAD_DATA_AREA, NULL);
			if (fs_Retval.ErrorCode == NoError) // upload successfully
        	{
        		upload_times--;
        		fs_Retval.ErrorCode = GeneralError; // wait for next upload
        		upload_nand_spare = FALSE; // clear it
        	}
			else // upload failed
			{
				FatalError(fs_Retval.ErrorCode);
			}
			
	        // Does not matter if we had an error. Boot anyway.
	        break;

		default:
			unknown_protocol_command(getProtocolCmd());
			FatalError(UnknownProtocolCmd);
	    }
	}while (fs_Retval.ErrorCode != NoError);

disconnect:
	HandleDisconnect();

shutdown:
    ShutdownPort(CI2_USB_D);

	return pBootImageInfo;
}
Beispiel #10
0
quint64 CTcpClient::SendData( const char * data, qint64 maxSize )
{
    HandleDisconnect( );
    return write( data, maxSize );
}