Beispiel #1
0
bool CommonFunctions::WaitAndConnect(RakPeerInterface *peer,char* ip,unsigned short int port,int millisecondsToWait)
{

	SystemAddress connectToAddress;

	connectToAddress.SetBinaryAddress(ip);
	connectToAddress.port=port;
	TimeMS entryTime=GetTimeMS();

	while(!CommonFunctions::ConnectionStateMatchesOptions (peer,connectToAddress,true)&&GetTimeMS()-entryTime<millisecondsToWait)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (peer,connectToAddress,true,true,true,true))
		{
			peer->Connect(ip,port,0,0);
		}

		RakSleep(100);

	}

	if (ConnectionStateMatchesOptions (peer,connectToAddress,true))
	{
		return 1;
	}

	return 0;
}
Beispiel #2
0
extern "C" void ylog_log(ylog_t *ylog, ylog_output_level_t level, const char *file, int line, const char *func, const char *fmt, ...)
{
    MUTEX_LOCK(ylog->cb_mutex);

    if (level > ylog->level) {
        MUTEX_UNLOCK(ylog->cb_mutex);
        return;
    }

    ylog->buf[BUF_LEN-1] = '\0';
    switch(level) {
        case 0:
            strcpy(ylog->buf, "[ERROR] ");
            break;
        case 1:
            strcpy(ylog->buf, "[ INFO] ");
            break;
        case 2:
            strcpy(ylog->buf, "[DEBUG] ");
            break;
        default:
            break;
    }

    const int level_str_len = 8;

    va_list ap;
    va_start(ap, fmt);
    int offset = vsnprintf(ylog->buf + level_str_len,
            BUF_LEN - 129- level_str_len, fmt, ap);
    va_end(ap);

    if (ylog->position)
        snprintf(ylog->buf + level_str_len + offset, 128,
                "|  ..[%s:%d,%s]\n", file, line, func);
    else
        snprintf(ylog->buf + level_str_len + offset, 128, "\n");

    if (ylog->fold) {
        if (!strncmp(ylog->buf, ylog->cache, BUF_LEN)) {
            ylog->repeat_counter++;
        }
        else {
            repeat_log_flush(ylog);
            ylog->cb(ylog->caller, level, ylog->start_millisecond,
                    ylog->timer ? GetTimeMS()-ylog->start_millisecond : 0,
                    ylog->buf);
            strcpy(ylog->cache, ylog->buf);
            ylog->repeat_counter = 0;
            ylog->repeat_level = level;
        }
    }
    else {
        ylog->cb(ylog->caller, level, ylog->start_millisecond,
                ylog->timer ? GetTimeMS()-ylog->start_millisecond : 0,
                ylog->buf);
    }

    MUTEX_UNLOCK(ylog->cb_mutex);
}
/* Busy wait (not sleep) until the given time has elapsed */
double  BusyWait( double durationMS ) {
	double stopTimeMS = GetTimeMS() + durationMS;
	double time;
	assert( _hrtInitialized );
	// Repeat until duration is reached
	do {
		time = GetTimeMS();
	} while ( time < stopTimeMS );
	return time;

}
/* Sleep until the given time has elapsed from the start of the hyperperiod */
double NanoSleep( double deadlineMS ) {
	int retVal = 0;
	struct timespec timeVal, currentTimeAT;
	// Get the current time
	clock_gettime( CLOCK_REALTIME, &currentTimeAT );
	// Get difference between current time and startAT (start of hyperperiod)
	long differenceNS = currentTimeAT.tv_nsec - _startAT.tv_nsec;
	double differenceSec = difftime( currentTimeAT.tv_sec, _startAT.tv_sec );
	// Convert difference to long and NS
	long currentNS = (long)(differenceSec * 1000000000.0) + differenceNS;
	long deadlineNS = deadlineMS * 1000000;
	long toleranceNS = SCHEDULER_RESOLUTION_MS * 1000000;
	// Make sure clock has been initialized
	assert( _hrtInitialized );
	assert( deadlineMS >= 0.0 );
	// Make sure we are not calling this too late
	if ( currentNS > deadlineNS + toleranceNS ){
		double currentTimeMS = (double)currentNS / 1000000.0;
		// Signal that an error has occured
		_SchedErrorHandler( FS_ERR_SLEEPDEADLINEMISS, _nextInstance, deadlineMS );
		return currentTimeMS;
	}
	// Sleep until the deadline is reached
	timeVal.tv_sec = _startAT.tv_sec;
	timeVal.tv_nsec = _startAT.tv_nsec + deadlineNS;
	// Must normalize timeVal
	tsnorm( &timeVal );
	// Call the actual clock_nanosleep function (with absolute time value, not relative)
	do {
		retVal = clock_nanosleep( CLOCK_REALTIME, TIMER_ABSTIME, &timeVal, NULL );
	} while ( retVal != 0 );
	// Return the current time
	return GetTimeMS();
}
Beispiel #5
0
void CTimeEv::UpdateAVIFrame()
{
	//time corresponds to red bar in middle of window
	int iFrame = -m_iFrameOffset + GetTimeMS() / m_oAVIR.MSPerFrame() ;
	if(iFrame < m_oAVIR.LastFrame() && iFrame >= m_oAVIR.FirstFrame())
		m_oAVIR.GoToFrame(iFrame);
	else
	{
		Write2Log("Out of frames at fMilliSeconds=%5.3f, m_iFrameOffset=%d",GetTimeMS(),m_iFrameOffset);
		//char msg[1024];
		//sprintf(msg,"Out of frames at fMilliSeconds=%5.3f!",fMilliSeconds);
		//MessageBox(msg);
		//KillTimer(IDT_PLAY);
		//pMode = 0;
		//SetDlgItemText(IDC_TE_PLAY,TEXT("&Play"));
	}
	InvalidateRect(m_videoRect,false);		
}
/* Process the reception of a message */
void FROLogger::ProcessMessage( char* buffer, uint32_t messageSize, char* sender ) {
    uint16_t msgID;
    // Get the message ID
    memcpy( &msgID, buffer, sizeof(uint16_t) );
    // Switch on the message type
    switch ( msgID ) {
    case SyncReady:
        printf( "%s @ %4.3f : SyncReady\n", sender, GetTimeMS() );
        break;
    case SyncAck:
        printf( "%s @ %4.3f : SyncAck\n", sender, GetTimeMS() );
        break;
    case SyncStart:
        printf( "%s @ %4.3f : SyncStart\n", sender, GetTimeMS() );
        printf( "----------------------------------------------------\n" );
        ZeroTime( 0.0 );
        break;
    case SyncHalt:
        printf( "----------------------------------------------------\n" );
        printf( "%s @ %4.3f : SyncHalt\n", sender, GetTimeMS() );
        this->HaltExecution();
        break;
    default:
        // Can we find the message ID in the map
        std::map<uint16_t,FLMessageType>::iterator messageIter = this->_messageTypes.find( msgID );
        if ( messageIter != this->_messageTypes.end() ) {
            // Process each element
            for ( int i = 0; i < (*messageIter).second.NumElement(); i++ ) {
                // Handle the detailed processing into message structures
                FLMessageElement element = (*messageIter).second.Element( i );
                // Is the element a double
                if ( element.type == "double" ) {
                    double data;
                    memcpy( &data, buffer + sizeof(msgID) + element.offset, sizeof(double) );
                    printf( "%s @ %4.3f : %d = %4.3f \n", sender, GetTimeMS(), msgID, data );
                }
                else printf( "Error!!!\n" );
            }

        }
        break;
    }
}
Beispiel #7
0
// Worker thread to capture fingerprint image
static void *ScanThread( void *arg )
{
	unsigned long ulErr;
	long lT1, lT2;
	char szOthers[64]="";

	while( 1 )
	{
		if (bStop)
			break;	
	
		gdk_threads_enter();
		//
		ulErr = 0;
		memset(raw_data, 0, ImageSize.nImageSize );
		lT1 = GetTimeMS();
		if ( !ftrScanGetFrame(hDevice, raw_data, NULL) )
			ulErr = ftrScanGetLastError();
		lT2 = GetTimeMS();
		memset(szOthers, 0, 64);
		if( dwLfdLevel == FTR_LFD_LEVEL_2 )
		{
		    FTRSCAN_PROPERTY_LFD_SW_1_DATA PropertyData;
			if( ftrScanGetProperty( hDevice, FTR_PROPERTY_LFD_SW_1_CALCULATED_DATA, &PropertyData ) )
			{
				sprintf( szOthers, ". Time %ld(ms)\nCalculated: %lu", lT2-lT1, PropertyData.dwStrength );
			}
			else
				sprintf( szOthers, ". Time %ld(ms)\nCalculated:------", lT2-lT1 );
		}
		else
			sprintf( szOthers, ". Time %ld(ms)\nCalculated:------", lT2-lT1 );
		ShowMsg( ulErr, szOthers );
		draw_fp_image();
		// syncing with X server 
		gdk_flush();
		gdk_threads_leave();
		// 
		usleep(100);
	}
	pthread_exit(0);
	return NULL;
}
Beispiel #8
0
static void repeat_log_flush(ylog_t *ylog)
{
    if (ylog->repeat_counter > 0) {
        char buf_repeat[64];
        snprintf(buf_repeat, sizeof(buf_repeat), "<repeat %d times>\n",
                ylog->repeat_counter + 1);
        ylog->cb(ylog->caller, ylog->repeat_level, ylog->start_millisecond,
                ylog->timer ? GetTimeMS()-ylog->start_millisecond : 0,
                buf_repeat);
    }
}
Beispiel #9
0
//use time for IR sensor value if using TRIP
void WallFollow(int mode, int time, int dir){
	 int startTime, diff, close;
	 switch(mode){
		 case NEVER:
		 while(1){
		 	 diff = WallFollowPID(  ADS7830_Values[FRONT_LEFT] -  ADS7830_Values[BACK_LEFT], P9v , 0 , D12v , divP12v, 1 , divD12v);
		 	 close = 0;//WallFollowPID2( IDEAL_DISTANCE - (ADS7830_Values[FRONT_LEFT] + ADS7830_Values[BACK_LEFT]) , 1 , 0 , 0, 1 , 0 , 0);
			 UARTprintf("Back Left: %d Front_Left: %d, close: %d, diff: %d\n",ADS7830_Values[BACK_LEFT], ADS7830_Values[FRONT_LEFT], close, diff);
			 SetMotorPowersBlocking( dir*(127 + diff + close) ,dir*(127 - diff - close));
		 }
		 //break;
		 case CHARGING:
		 while(!Charging()){
		 	 diff = WallFollowPID(  ADS7830_Values[FRONT_LEFT] -  ADS7830_Values[BACK_LEFT], P9v , 0 , D12v , divP12v, 1 , divD12v);
		 	 close = 0;//WallFollowPID2( IDEAL_DISTANCE - (ADS7830_Values[FRONT_LEFT] + ADS7830_Values[BACK_LEFT]) , 1 , 0 , 0, 1 , 0 , 0);
			 UARTprintf("Back Left: %d Front_Left: %d, close: %d, diff: %d\n",ADS7830_Values[BACK_LEFT], ADS7830_Values[FRONT_LEFT], close, diff);
			 SetMotorPowersBlocking( dir*(127 + diff + close) ,dir*(127 - diff - close));
		 }
		 break;
		 case TIMEOUT:
		 startTime = GetTimeMS();
		 while(GetTimeMS()<startTime+time){
		 	 diff = WallFollowPID(  ADS7830_Values[FRONT_LEFT] -  ADS7830_Values[BACK_LEFT], P9v , 0 , D12v , divP12v, 1 , divD12v);
		 	 close = 0;//WallFollowPID2( IDEAL_DISTANCE - (ADS7830_Values[FRONT_LEFT] + ADS7830_Values[BACK_LEFT]) , 1 , 0 , 0, 1 , 0 , 0);
			 UARTprintf("Back Left: %d Front_Left: %d, close: %d, diff: %d\n",ADS7830_Values[BACK_LEFT], ADS7830_Values[FRONT_LEFT], close, diff);
			 SetMotorPowersBlocking( dir*(127 + diff + close) ,dir*(127 - diff - close));
		 }
		 break;
		 case TRIP:
		 while(!tripped(time,LOWER)){
		 	 diff = WallFollowPID(  ADS7830_Values[FRONT_LEFT] -  ADS7830_Values[BACK_LEFT], P9v , 0 , D12v , divP12v, 1 , divD12v);
		 	 close = 0;//WallFollowPID2( IDEAL_DISTANCE - (ADS7830_Values[FRONT_LEFT] + ADS7830_Values[BACK_LEFT]) , 1 , 0 , 0, 1 , 0 , 0);
			 UARTprintf("Back Left: %d Front_Left: %d, close: %d, diff: %d\n",ADS7830_Values[BACK_LEFT], ADS7830_Values[FRONT_LEFT], close, diff);
			 SetMotorPowersBlocking( dir*(127 + diff + close) ,dir*(127 - diff - close));
		 }
		 break;

	 }
}
Beispiel #10
0
static noinline void DoLog(const mpt::log::Context &context, std::wstring message)
//--------------------------------------------------------------------------------
{
	// remove eol if already present
	message = mpt::String::RTrim(message, L"\r\n");
	#if defined(MODPLUG_TRACKER)
		static uint64_t s_lastlogtime = 0;
		uint64 cur = GetTimeMS();
		uint64 diff = cur - s_lastlogtime;
		s_lastlogtime = cur;
		#ifdef LOG_TO_FILE
		{
			static FILE * s_logfile = nullptr;
			if(!s_logfile)
			{
				s_logfile = mpt_fopen(MPT_PATHSTRING("mptrack.log"), "a");
			}
			if(s_logfile)
			{
				fprintf(s_logfile, "%s+%s %s(%i): %s [%s]\n", TimeAsAsString(cur).c_str(), TimeDiffAsString(diff).c_str(), context.file, context.line, mpt::To(mpt::CharsetUTF8, message).c_str(), context.function);
				fflush(s_logfile);
			}
		}
		#endif // LOG_TO_FILE
		{
			OutputDebugStringW(mpt::String::PrintW(L"%1(%2): +%3 %4 [%5]\n", mpt::ToWide(mpt::CharsetASCII, context.file), context.line, TimeDiffAsStringW(diff), message, mpt::ToWide(mpt::CharsetASCII, context.function)).c_str());
		}
	#else // !MODPLUG_TRACKER
		std::clog
			<< "openmpt: "
			<< context.file << "(" << context.line << ")" << ": "
#if defined(MPT_WITH_CHARSET_LOCALE)
			<< mpt::ToLocale(message)
#else
			<< mpt::To(mpt::CharsetUTF8, message)
#endif
			<< " [" << context.function << "]"
			<< std::endl;
	#endif // MODPLUG_TRACKER
}
Beispiel #11
0
extern "C" ylog_t *ylog_open(void *caller, ylog_output_level_t level, ylog_output_position_t pos, ylog_output_time_t timer, ylog_output_fold_t fold, ylog_callback_t cb)
{
    if (!cb)
        return NULL;

    ylog_t *ylog = (ylog_t *)malloc(sizeof(ylog_t));
    ylog->caller = caller;
    ylog->level = level;
    ylog->position = (pos != 0);
    ylog->timer = (timer != 0);
    ylog->fold = (fold != 0);
    ylog->cb = cb;

    ylog->start_millisecond = GetTimeMS();
    MUTEX_CREATE(ylog->cb_mutex);

    ylog->buf = (char *)calloc(1, BUF_LEN);
    ylog->cache = (char *)calloc(1, BUF_LEN);
    ylog->repeat_counter = 0;

    return ylog;
}
Beispiel #12
0
void CTimeEv::OnBnClickedButtonVidDlgOpen()
{
	// TODO: Add your control notification handler code here
	m_oAVIR.Close(); //close before re-opening

	static char BASED_CODE szFilter[] = "AVI video files (*.avi)|*.avi|All Files (*.*)|*.*||";
	CFileDialog dlg(TRUE, "avi", "*.avi", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,szFilter);
	if(dlg.DoModal()!=IDOK)
		return;

	CString cstrAVIPath=dlg.GetPathName();
	CString strMsg;

	if(!m_oAVIR.Open(cstrAVIPath))
	{	strMsg.Format("Couldn't open %s",cstrAVIPath);
		MessageBox(strMsg);
	}
	else
	{
		float fMilliSeconds = GetTimeMS();
		m_iFrameOffset = fMilliSeconds / m_oAVIR.MSPerFrame() ;
		
		strMsg.Format("Opened %s w=%d h=%d firstf=%d lastf=%d",
			cstrAVIPath,
			m_oAVIR.Width(),
			m_oAVIR.Height(),
			m_oAVIR.FirstFrame(),
			m_oAVIR.LastFrame());
		Write2Log(strMsg);

		Write2Log("timeWindow=%d, time=%.2f, m_iFrameOffset=%d",timeWindow,fMilliSeconds,m_iFrameOffset);

		InvalidateRect(NULL,FALSE);

		if(!m_hdd)
			m_hdd=DrawDibOpen();
	}
}
/*
Description: Tests what happens if two instances of RakNet connect to each other at the same time. This has caused handshaking problems in the past.

Success conditions:
Everything connects and sends normally.

Failure conditions:
Expected values from ping/pong do not occur within expected time.
*/
int CrossConnectionConvertTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	static const unsigned short SERVER_PORT=1234;
	//	char serverMode[32];
	char serverIP[64];

	strcpy(serverIP,"127.0.0.1");	

	char clientIP[64];
	RakPeerInterface *server,*client;
	unsigned short clientPort;
	bool gotNotification;
	server=RakPeerInterface::GetInstance();
	destroyList.Clear(false,_FILE_AND_LINE_);
	destroyList.Push(server,_FILE_AND_LINE_);
	client=RakPeerInterface::GetInstance();
	destroyList.Push(client,_FILE_AND_LINE_);

	

	server->Startup(1,&SocketDescriptor(SERVER_PORT,0), 1);
	server->SetMaximumIncomingConnections(1);

	client->Startup(1,&SocketDescriptor(0,0), 1);

	client->Ping(serverIP,SERVER_PORT,false);

	//	PacketLogger pl;
	//	pl.LogHeader();
	//	rakPeer->AttachPlugin(&pl);

	TimeMS connectionAttemptTime=0,connectionResultDeterminationTime=0,nextTestStartTime=0;

	TimeMS entryTime=GetTimeMS();//Loop entry time

	bool printedYet=false;
	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		Packet *p;

		printedYet=false;

		for (p=server->Receive(); p; server->DeallocatePacket(p), p=server->Receive())
		{

			if (isVerbose&&!printedYet)
			{
				printf("Server:\n");
				printedYet=true;
			}
			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
			{

				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{

				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_UNCONNECTED_PING)
			{

				if (isVerbose)
					printf("ID_PING\n");
				connectionAttemptTime=GetTimeMS()+1000;
				p->systemAddress.ToString(false,clientIP);
				clientPort=p->systemAddress.port;
				gotNotification=false;
			}
			else if (p->data[0]==ID_UNCONNECTED_PONG)
			{

				if (isVerbose)
					printf("ID_UNCONNECTED_PONG\n");
				TimeMS sendPingTime;
				BitStream bs(p->data,p->length,false);
				bs.IgnoreBytes(1);
				bs.Read(sendPingTime);
				TimeMS rtt = GetTimeMS() - sendPingTime;
				if (rtt/2<=500)
					connectionAttemptTime=GetTimeMS()+1000-rtt/2;
				else
					connectionAttemptTime=GetTimeMS();
				gotNotification=false;
			}
		}

		printedYet=false;
		for (p=client->Receive(); p; client->DeallocatePacket(p), p=client->Receive())
		{

			if (isVerbose&&!printedYet)
			{
				printf("Client:\n");
				printedYet=true;
			}
			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
			{

				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{

				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_UNCONNECTED_PING)
			{

				if (isVerbose)
					printf("ID_PING\n");
				connectionAttemptTime=GetTimeMS()+1000;
				p->systemAddress.ToString(false,clientIP);
				clientPort=p->systemAddress.port;
				gotNotification=false;
			}
			else if (p->data[0]==ID_UNCONNECTED_PONG)
			{

				if (isVerbose)
					printf("ID_UNCONNECTED_PONG\n");
				TimeMS sendPingTime;
				BitStream bs(p->data,p->length,false);
				bs.IgnoreBytes(1);
				bs.Read(sendPingTime);
				TimeMS rtt = GetTimeMS() - sendPingTime;
				if (rtt/2<=500)
					connectionAttemptTime=GetTimeMS()+1000-rtt/2;
				else
					connectionAttemptTime=GetTimeMS();
				gotNotification=false;
			}
		}

		if (connectionAttemptTime!=0 && GetTimeMS()>=connectionAttemptTime)
		{

			if (isVerbose)
				printf("Attemping connection\n");
			connectionAttemptTime=0;

			server->Connect(clientIP,clientPort,0,0);
			client->Connect(serverIP,SERVER_PORT,0,0);

			connectionResultDeterminationTime=GetTimeMS()+2000;
		}
		if (connectionResultDeterminationTime!=0 && GetTimeMS()>=connectionResultDeterminationTime)
		{
			connectionResultDeterminationTime=0;
			if (gotNotification==false)
			{
				DebugTools::ShowError("Did not recieve expected response. \n",!noPauses && isVerbose,__LINE__,__FILE__);
				return 1;
			}

			SystemAddress sa;
			sa.SetBinaryAddress(serverIP);
			sa.port=SERVER_PORT;
			client->CancelConnectionAttempt(sa);

			sa.SetBinaryAddress(clientIP);
			sa.port=clientPort;
			server->CancelConnectionAttempt(sa);

			server->CloseConnection(server->GetSystemAddressFromIndex(0),true,0);
			client->CloseConnection(client->GetSystemAddressFromIndex(0),true,0);

			//if (isServer==false)
			nextTestStartTime=GetTimeMS()+1000;

		}
		if (nextTestStartTime!=0 && GetTimeMS()>=nextTestStartTime)
		{
			client->Ping(serverIP,SERVER_PORT,false);
			nextTestStartTime=0;
		}
		RakSleep(0);

	}
	if (isVerbose)
		printf("Test succeeded.\n");

	return 0;

}
int DroppedConnectionConvertTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *server;
	RakPeerInterface *clients[NUMBER_OF_CLIENTS];
	unsigned index, connectionCount;
	SystemAddress serverID;
	Packet *p;
	unsigned short numberOfSystems;
	unsigned short numberOfSystems2;
	int sender;

	// Buffer for input (an ugly hack to keep *nix happy)
	//	char buff[256];

	// Used to refer to systems.  We already know the IP
	unsigned short serverPort = 20000;
	serverID.binaryAddress=inet_addr("127.0.0.1");
	serverID.port=serverPort;

	server=RakPeerInterface::GetInstance();
	destroyList.Clear(false,_FILE_AND_LINE_);
	destroyList.Push(server,_FILE_AND_LINE_);
	//	server->InitializeSecurity(0,0,0,0);
	SocketDescriptor socketDescriptor(serverPort,0);
	server->Startup(NUMBER_OF_CLIENTS, &socketDescriptor, 1);
	server->SetMaximumIncomingConnections(NUMBER_OF_CLIENTS);
	server->SetTimeoutTime(2000,UNASSIGNED_SYSTEM_ADDRESS);

	for (index=0; index < NUMBER_OF_CLIENTS; index++)
	{
		clients[index]=RakPeerInterface::GetInstance();
		destroyList.Push(clients[index],_FILE_AND_LINE_);
		SocketDescriptor socketDescriptor2(serverPort+1+index,0);
		clients[index]->Startup(1, &socketDescriptor2, 1);
		if (clients[index]->Connect("127.0.0.1", serverPort, 0, 0)!=CONNECTION_ATTEMPT_STARTED)
		{
			DebugTools::ShowError("Connect function failed.",!noPauses && isVerbose,__LINE__,__FILE__);
			return 2;

		}
		clients[index]->SetTimeoutTime(5000,UNASSIGNED_SYSTEM_ADDRESS);

		RakSleep(1000);
		if (isVerbose)
			printf("%i. ", index);
	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	int seed = 12345;
	if (isVerbose)
		printf("Using seed %i\n", seed);
	seedMT(seed);//specify seed to keep execution path the same.

	int randomTest;

	bool dropTest=false;
	RakTimer timeoutWaitTimer(1000);

	while (GetTimeMS()-entryTime<30000)//run for 30 seconds.
	{
		// User input

		randomTest=randomMT() %4;

		if(dropTest)
		{

			server->GetConnectionList(0, &numberOfSystems);
			numberOfSystems2=numberOfSystems;

			connectionCount=0;
			for (index=0; index < NUMBER_OF_CLIENTS; index++)
			{
				clients[index]->GetConnectionList(0, &numberOfSystems);
				if (numberOfSystems>1)
				{
					if (isVerbose)
					{
						printf("Client %i has %i connections\n", index, numberOfSystems);
						DebugTools::ShowError("Client has more than one connection",!noPauses && isVerbose,__LINE__,__FILE__);
						return 1;
					}

				}
				if (numberOfSystems==1)
				{
					connectionCount++;
				}
			}

			if (connectionCount!=numberOfSystems2)
			{
				if (isVerbose)
					DebugTools::ShowError("Timeout on dropped clients not detected",!noPauses && isVerbose,__LINE__,__FILE__);
				return 3;
			}

		}
		dropTest=false;

		switch(randomTest)
		{

		case 0:
			{
				index = randomMT() % NUMBER_OF_CLIENTS;

				clients[index]->GetConnectionList(0, &numberOfSystems);
				clients[index]->CloseConnection(serverID, false,0);
				if (numberOfSystems==0)
				{
					if (isVerbose)
						printf("Client %i silently closing inactive connection.\n",index);
				}
				else
				{
					if (isVerbose)
						printf("Client %i silently closing active connection.\n",index);
				}
			}

			break;
		case 1:
			{
				index = randomMT() % NUMBER_OF_CLIENTS;

				clients[index]->GetConnectionList(0, &numberOfSystems);

				if(!CommonFunctions::ConnectionStateMatchesOptions (clients[index],serverID,true,true,true,true) )//Are we connected or is there a pending operation ?
				{
					if (clients[index]->Connect("127.0.0.1", serverPort, 0, 0)!=CONNECTION_ATTEMPT_STARTED)
					{

						DebugTools::ShowError("Connect function failed.",!noPauses && isVerbose,__LINE__,__FILE__);
						return 2;

					}
				}
				if (numberOfSystems==0)
				{
					if (isVerbose)
						printf("Client %i connecting to same existing connection.\n",index);

				}
				else
				{
					if (isVerbose)
						printf("Client %i connecting to closed connection.\n",index);
				}
			}

			break;
		case 2:
			{

				if (isVerbose)
					printf("Randomly connecting and disconnecting each client\n");
				for (index=0; index < NUMBER_OF_CLIENTS; index++)
				{
					if (NUMBER_OF_CLIENTS==1 || (randomMT()%2)==0)
					{
						if (clients[index]->IsActive())
						{

							int randomTest2=randomMT() %2;
							if (randomTest2)
								clients[index]->CloseConnection(serverID, false, 0);
							else
								clients[index]->CloseConnection(serverID, true, 0);
						}
					}
					else
					{
						if(!CommonFunctions::ConnectionStateMatchesOptions (clients[index],serverID,true,true,true,true) )//Are we connected or is there a pending operation ?
						{
							if (clients[index]->Connect("127.0.0.1", serverPort, 0, 0)!=CONNECTION_ATTEMPT_STARTED)
							{
								DebugTools::ShowError("Connect function failed.",!noPauses && isVerbose,__LINE__,__FILE__);
								return 2;

							}
						}
					}
				}
			}
			break;

		case 3:
			{

				if (isVerbose)
					printf("Testing if clients dropped after timeout.\n");
				timeoutWaitTimer.Start();
						//Wait half the timeout time, the other half after receive so we don't drop all connections only missing ones, Active ait so the threads run on linux
				while (!timeoutWaitTimer.IsExpired())
				{
				RakSleep(50);
				}
				dropTest=true;

			}
			break;
		default:
			// Ignore anything else
			break;
		}

		server->GetConnectionList(0, &numberOfSystems);
		numberOfSystems2=numberOfSystems;
		if (isVerbose)
			printf("The server thinks %i clients are connected.\n", numberOfSystems);
		connectionCount=0;
		for (index=0; index < NUMBER_OF_CLIENTS; index++)
		{
			clients[index]->GetConnectionList(0, &numberOfSystems);
			if (numberOfSystems>1)
			{
				if (isVerbose)
				{
					printf("Client %i has %i connections\n", index, numberOfSystems);
					DebugTools::ShowError("Client has more than one connection",!noPauses && isVerbose,__LINE__,__FILE__);
					return 1;
				}

			}
			if (numberOfSystems==1)
			{
				connectionCount++;
			}
		}

		if (isVerbose)
			printf("%i clients are actually connected.\n", connectionCount);
		if (isVerbose)
			printf("server->NumberOfConnections==%i.\n", server->NumberOfConnections());

		//}

		// Parse messages

		while (1)
		{
			p = server->Receive();
			sender=NUMBER_OF_CLIENTS;
			if (p==0)
			{
				for (index=0; index < NUMBER_OF_CLIENTS; index++)
				{
					p = clients[index]->Receive();
					if (p!=0)
					{
						sender=index;
						break;						
					}
				}
			}

			if (p)
			{
				switch (p->data[0])
				{
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)
						printf("%i: %ID_CONNECTION_REQUEST_ACCEPTED from %i.\n",sender, p->systemAddress.port);
					break;
				case ID_DISCONNECTION_NOTIFICATION:
					// Connection lost normally
					if (isVerbose)
						printf("%i: ID_DISCONNECTION_NOTIFICATION from %i.\n",sender, p->systemAddress.port);
					break;

				case ID_NEW_INCOMING_CONNECTION:
					// Somebody connected.  We have their IP now
					if (isVerbose)
						printf("%i: ID_NEW_INCOMING_CONNECTION from %i.\n",sender, p->systemAddress.port);
					break;


				case ID_CONNECTION_LOST:
					// Couldn't deliver a reliable packet - i.e. the other system was abnormally
					// terminated
					if (isVerbose)
						printf("%i: ID_CONNECTION_LOST from %i.\n",sender, p->systemAddress.port);
					break;

				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)
						printf("%i: ID_NO_FREE_INCOMING_CONNECTIONS from %i.\n",sender, p->systemAddress.port);
					break;

				default:
					// Ignore anything else
					break;
				}
			}
			else
				break;

			if (sender==NUMBER_OF_CLIENTS)
				server->DeallocatePacket(p);
			else
				clients[sender]->DeallocatePacket(p);
		}
		if (dropTest)
		{
			//Trigger the timeout if no recieve
			timeoutWaitTimer.Start();
			while (!timeoutWaitTimer.IsExpired())
			{
			RakSleep(50);
			}
		}
		// 11/29/05 - No longer necessary since I added the keepalive
		/*
		// Have everyone send a reliable packet so dropped connections are noticed.
		ch=255;
		server->Send((char*)&ch, 1, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);

		for (index=0; index < NUMBER_OF_CLIENTS; index++)
		clients[index]->Send((char*)&ch, 1, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		*/

		// Sleep so this loop doesn't take up all the CPU time

		RakSleep(10);

	}

	return 0;
}
Beispiel #15
0
void CTimeEv::OnPaint() 
{
	CPaintDC dc(this); // device context for painting

	GetClientRect(m_MainRect);
	m_SpikesRect = m_MainRect;
	m_SpikesRect.left += 11;
	m_SpikesRect.top += 11;
	m_SpikesRect.right -= 100; // -10
	m_SpikesRect.bottom -= 219; //  179; // 209

	CDC dcTemp;
	CBitmap bmTemp;
	bmTemp.CreateCompatibleBitmap(&dc,m_SpikesRect.right,m_SpikesRect.bottom);
	dcTemp.CreateCompatibleDC(&dc);
	CBitmap* bmOld = dcTemp.SelectObject(&bmTemp);
	
	// main RECTANGLE
	dcTemp.Rectangle(m_SpikesRect);
	
	m_SpikesRect.left += 1;
	m_SpikesRect.right -= 1;
	m_SpikesRect.bottom -= 1;
	m_SpikesRect.top += 1;

	// AXIS for SCALE
	int raster = m_SpikesRect.Width() / 10;
	CPen rasterPen(PS_SOLID,1, RGB(230,230,230)) , rasterPenRed(PS_SOLID,1,RGB(200,0,0));
	CPen *pOldRasterPen = dcTemp.SelectObject(&rasterPen);
	for (int iRaster = 1; iRaster < 10; iRaster++)
	{	if(iRaster==5) //paint middle line as red
		{	dcTemp.SelectObject(&rasterPenRed);
			dcTemp.MoveTo(m_SpikesRect.left + iRaster*raster, m_SpikesRect.top);
			dcTemp.LineTo(m_SpikesRect.left + iRaster*raster, m_SpikesRect.bottom);
			dcTemp.SelectObject(&rasterPen);
		}
		else	//paint other lines as gray
		{	dcTemp.MoveTo(m_SpikesRect.left + iRaster*raster, m_SpikesRect.top);
			dcTemp.LineTo(m_SpikesRect.left + iRaster*raster, m_SpikesRect.bottom);
		}
	}
	dcTemp.SelectObject(pOldRasterPen);

	m_ArenaRect = m_MainRect;
	m_ArenaRect.left += 280;
	m_ArenaRect.bottom -= 47;  // 45
	m_ArenaRect.top = m_ArenaRect.bottom - 130; 
	m_ArenaRect.right = m_ArenaRect.left + 130;
	m_ArenaRect.left += 1;
	m_ArenaRect.top += 1;
	m_ArenaRect.right -= 1;
	m_ArenaRect.bottom -= 1;

	m_RoomRect = m_MainRect;
	m_RoomRect.left += 11;
	m_RoomRect.bottom -= 47; //45
	m_RoomRect.top = m_RoomRect.bottom - 130; 
	m_RoomRect.right = m_RoomRect.left + 130;
	m_RoomRect.left += 1;
	m_RoomRect.top += 1;
	m_RoomRect.right -= 1;
	m_RoomRect.bottom -= 1;

	int oldBkMode = dc.SetBkMode( TRANSPARENT );
	dc.TextOut(m_ArenaRect.left, m_ArenaRect.top - 10, "Arena");
	dc.TextOut(m_RoomRect.left, m_RoomRect.top - 10, "Room");
	dc.TextOut(m_MainRect.right - 227, m_MainRect.bottom - 207, "Time window [ms]");
	dc.TextOut(m_MainRect.right - 167, m_MainRect.bottom - 137, "PlaySpeed");
	dc.SetBkMode( oldBkMode );

	unsigned char checked = 0;
	char			params;
	unsigned char	spikesCh, eegCh;
	CRect			signalRect = m_SpikesRect;
	float oneWinY = 0.0f;
	
	if(mPrepareFlag)
		checked = GetParameters( & spikesCh, & eegCh );
	
	if (checked)
	{
		oneWinY = m_SpikesRect.Height() / ( spikesCh + eegCh );

		dc.Ellipse(m_ArenaRect);
		dc.Ellipse(m_RoomRect);

		// Arena win
		if ( (m_MainDataStack->InBpfExist & 1) || (m_MainDataStack->LoadedAdd & 1) )
		{
			params = 2; // iixxxooo, xxx - points/circles/vectors, ooo - arena/room
			params += 8 * m_wndCmbArena.GetCurSel();
				m_MainDataStack->m_MainSyncStack.DrawArenaRoom(&dc,m_ArenaRect, timeStampFirst + 10*startTime, timeWindow, params, &clView[0], m_MainDataStack->whichDraw);
		}

		// Room win
		if ( (m_MainDataStack->InBpfExist & 2) || (m_MainDataStack->LoadedAdd & 2) )
		{
			params = 4; // iixxxooo, xxx - points/circles/vectors, ooo - arena/room
			params += 8 * m_wndCmbRoom.GetCurSel();
				m_MainDataStack->m_MainSyncStack.DrawArenaRoom(&dc,m_RoomRect, timeStampFirst + 10*startTime, timeWindow, params, &clView[0], m_MainDataStack->whichDraw);
		}

		if ( spikesCh > 0 )
		{
			//	Spike win
			//	params : xxeeeeii, ii - R/S, eeee - electrode to show
			if ( timeWindow / MIN_TIME_WINDOW < 50 )
			{
				if ( !m_wndCheckSpike.GetCheck() )	// choice of R/S
					params = 0; // Raster
				else{
					if ( m_wndCheckRaster.GetCheck() )
						params = 1; // R/S
					else 
						params = 2; // Spike
				}
			}
			else
				params = 0;
			unsigned char bite = 4; // 100 b
			for ( int i = 0; i < m_MainDataStack->NUM_CHANNELS; i++ )
				params |= (m_wndListScale.GetCheck( i )) ? ( bite << i ) : 0 ;
			signalRect.bottom = spikesCh * (m_SpikesRect.bottom - m_SpikesRect.top) / checked;
			switch(m_MainDataStack->whichDraw)
			{
			case CLUST_ORIG:
			case CLUST_USER:
				m_MainDataStack->DrawTimeSpikes(&dcTemp, signalRect, startTime, timeWindow, timeStampFirst, params, &clView[0], &file);
				break;
			default:
				m_MainDataStack->DrawTimeSpikesAutoC(&dcTemp, signalRect, startTime, timeWindow, timeStampFirst, params, &clView[0], &file);
				break;
			}

			int j=0;
			for (i = 0; i < spikesCh; i++)
			{
				while ( !m_wndListScale.GetCheck( j ) )
					j++;
				char textCh[10];
				sprintf(textCh,"ch.%d",j+1);
				dcTemp.TextOut(m_SpikesRect.left + 1, m_SpikesRect.top + i * oneWinY,textCh);
				j++;
			}
		}

		if ( eegCh > 0 )
		{
			//	Spike win - EEG
			//	params : xxeeeeii, ii - R/S, eeee - electrode to show
			unsigned int paramInt=0;
			unsigned int bite = 4; // 100 b
			for ( int i = m_MainDataStack->NUM_CHANNELS; i < m_MainDataStack->NUM_CHANNELS + m_MainDataStack->m_MainEEGStack.GetChannels(); i++ )
				paramInt |= (m_wndListScale.GetCheck( i )) ? ( bite << (i-m_MainDataStack->NUM_CHANNELS) ) : 0;
			
			signalRect.top = spikesCh * (m_SpikesRect.bottom - m_SpikesRect.top) / checked;
			signalRect.bottom = m_SpikesRect.bottom;

			int iEEGChans = m_vEEGNames.size();
			double dGainSum = 0.0, dGainMin = 0.0;
			for(i=0;i<iEEGChans;i++)
			{
				if(!m_wndListScale.GetCheck( i + m_MainDataStack->NUM_CHANNELS))
					continue;
				dGainSum += m_vGainList[i];
				if(m_vGainList[i] < dGainMin)
					dGainMin = m_vGainList[i];
			}

			m_MainDataStack->m_MainEEGStack.DrawEEG(&dcTemp, signalRect, 10*startTime + timeStampFirst, timeWindow, paramInt, m_vGainList);

			int iYPos = m_SpikesRect.top + spikesCh*oneWinY;
			for (i = 0; i < iEEGChans; i++)
			{	if( !m_wndListScale.GetCheck( i + m_MainDataStack->NUM_CHANNELS) )
					continue;
				dcTemp.TextOut(m_SpikesRect.left + 1, iYPos ,m_vEEGNames[i].c_str());
				char textCh[32];
				sprintf(textCh,"%.1fX",m_vGainList[i]);
				dcTemp.TextOut(m_SpikesRect.right - 47, iYPos ,textCh);
				iYPos+=(m_vGainList[i]/dGainSum)*signalRect.Height();;
			}
		}
	}

	char textTime[20]; // time corresponds to middle of window
	sprintf(textTime,"time: %5.3f s", GetTimeMS()/1000.0 );
	dcTemp.TextOut(m_SpikesRect.left + 50,m_SpikesRect.top ,textTime);

	if(m_oAVIR.IsOpen())
		PaintVideoFrame(dc);

	dc.BitBlt(m_SpikesRect.left-1,m_SpikesRect.top-1,m_SpikesRect.Width()+2,m_SpikesRect.Height()+2,&dcTemp,m_SpikesRect.left-1,m_SpikesRect.top-1,SRCCOPY);
	dcTemp.SelectObject(bmOld);

//	char a[200];
//	sprintf(a,"%d " ,m_MainDataStack->FileType);
//	dc.TextOut(10,40,a);

	// Do not call cdxCSizingDialog::OnPaint() for painting messages
}
Beispiel #16
0
void CTimeUtils::UpdateFrameTime()
{
  frameTime = GetTimeMS();
}
/*
Description:

Tests:
virtual void RakPeerInterface::AddToSecurityExceptionList  	(  	const char *   	 ip  	 )   	
virtual void RakPeerInterface::AddToBanList  	(  	const char *   	 IP, 		TimeMS  	milliseconds = 0	  	) 	
virtual void RakPeerInterface::GetIncomingPassword  	(  	char *   	 passwordData, 		int *  	passwordDataLength	  	) 
virtual void RakPeerInterface::InitializeSecurity  	(  	const char *   	 pubKeyE, 		const char *  	pubKeyN, 		const char *  	privKeyP, 		const char *  	privKeyQ	  	) 			
virtual bool RakPeerInterface::IsBanned  	(  	const char *   	 IP  	 )   	 
virtual bool RakPeerInterface::IsInSecurityExceptionList  	(  	const char *   	 ip  	 )  
virtual void RakPeerInterface::RemoveFromSecurityExceptionList  	(  	const char *   	 ip  	 )  
virtual void RakPeerInterface::RemoveFromBanList  	(  	const char *   	 IP  	 )   
virtual void RakPeerInterface::SetIncomingPassword  	(  	const char *   	 passwordData, 		int  	passwordDataLength	  	) 	
virtual void 	ClearBanList (void)=0

Success conditions:
All functions pass tests.

Failure conditions:
Any function fails test.

Client connects with no password
Client connects with wrong password
Client failed to connect with correct password
Client was banned but connected anyways
GetIncomingPassword returned wrong password
IsBanned does not show localhost as banned
Localhost was not unbanned
Client failed to connect after banlist removal
Client failed to connect after banlist removal with clear function
Client did not connect encrypted
Client connected encrypted but shouldn't have
IsInSecurityExceptionList does not register localhost addition

RakPeerInterface Functions used, tested indirectly by its use:
Startup
SetMaximumIncomingConnections
Receive
DeallocatePacket
Send
IsConnected
GetStatistics

RakPeerInterface Functions Explicitly Tested:
SetIncomingPassword  
GetIncomingPassword  
AddToBanList
IsBanned
RemoveFromBanList  
ClearBanList 
InitializeSecurity  //Disabled because of RakNetStatistics changes 		 		
AddToSecurityExceptionList  //Disabled because of RakNetStatistics changes 		   	 
IsInSecurityExceptionList //Disabled because of RakNetStatistics changes 	  	  
RemoveFromSecurityExceptionList //Disabled because of RakNetStatistics changes 	  

*/
int SecurityFunctionsTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	char thePassword[]="password";
	server=RakPeerInterface::GetInstance();

	client=RakPeerInterface::GetInstance();

	client->Startup(1,&SocketDescriptor(),1);
	server->Startup(1,&SocketDescriptor(60000,0),1);
	server->SetMaximumIncomingConnections(1);
	server->SetIncomingPassword(thePassword,(int)strlen(thePassword));

	char returnedPass[22];
	int returnedLen=22;
	server->GetIncomingPassword(returnedPass,&returnedLen);
	returnedPass[returnedLen]=0;//Password is a data block convert to null terminated string to make the test easier

	if (strcmp(returnedPass,thePassword)!=0)
	{
		if (isVerbose)
		{

			printf("%s was returned but %s is the password\n",returnedPass,thePassword);
			DebugTools::ShowError("GetIncomingPassword returned wrong password\n",!noPauses && isVerbose,__LINE__,__FILE__);
		}
		return 5;
	}

	SystemAddress serverAddress;

	serverAddress.SetBinaryAddress("127.0.0.1");
	serverAddress.port=60000;
	TimeMS entryTime=GetTimeMS();

	if (isVerbose)
		printf("Testing if  no password is rejected\n");

	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,0,0);
		}

		RakSleep(100);

	}

	if (CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client connected with no password\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 1;
	}

	if (isVerbose)
		printf("Testing if incorrect password is rejected\n");

	char badPass[]="badpass";
	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,badPass,(int)strlen(badPass));
		}

		RakSleep(100);

	}

	if (CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client connected with wrong password\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 2;
	}

	if (isVerbose)
		printf("Testing if correct password is accepted\n");

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,(int)strlen(thePassword));
		}

		RakSleep(100);

	}

	if (!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client failed to connect with correct password\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 3;
	}

	while(CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))//disconnect client
	{

		client->CloseConnection (serverAddress,true,0,LOW_PRIORITY); 
	}

	if (isVerbose)
		printf("Testing if connection is rejected after adding to ban list\n");

	server->AddToBanList("127.0.0.1",0);

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,(int)strlen(thePassword));
		}

		RakSleep(100);

	}

	if(!server->IsBanned("127.0.0.1"))
	{

		if (isVerbose)
			DebugTools::ShowError("IsBanned does not show localhost as banned\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 6;

	}

	if (CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client was banned but connected anyways\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 4;
	}

	if (isVerbose)
		printf("Testing if connection is accepted after ban removal by RemoveFromBanList\n");

	server->RemoveFromBanList("127.0.0.1");
	if(server->IsBanned("127.0.0.1"))
	{

		if (isVerbose)
			DebugTools::ShowError("Localhost was not unbanned\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 7;

	}

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,(int)strlen(thePassword));
		}

		RakSleep(100);

	}

	if (!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client failed to connect after banlist removal\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 8;
	}

	while(CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))//disconnect client
	{

		client->CloseConnection (serverAddress,true,0,LOW_PRIORITY); 
	}

	if (isVerbose)
		printf("Testing if connection is rejected after adding to ban list\n");

	server->AddToBanList("127.0.0.1",0);

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,(int)strlen(thePassword));
		}

		RakSleep(100);

	}

	if(!server->IsBanned("127.0.0.1"))
	{

		if (isVerbose)
			DebugTools::ShowError("IsBanned does not show localhost as banned\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 6;

	}

	if (CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client was banned but connected anyways\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 4;
	}

	if (isVerbose)
		printf("Testing if connection is accepted after ban removal by ClearBanList\n");

	server->ClearBanList();
	if(server->IsBanned("127.0.0.1"))
	{

		if (isVerbose)
			DebugTools::ShowError("Localhost was not unbanned\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 7;

	}

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,(int)strlen(thePassword));
		}

		RakSleep(100);

	}

	if (!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true))
	{
		if (isVerbose)
			DebugTools::ShowError("Client failed to connect after banlist removal with clear function\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 9;
	}

	while(CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))//disconnect client
	{

		client->CloseConnection (serverAddress,true,0,LOW_PRIORITY); 
	}

/*//Disabled because of statistics changes

	if (isVerbose)
		printf("Testing InitializeSecurity on server\n");

	//-----------------------------

	// RSACrypt is a using namespace RakNet;
class that handles RSA encryption/decryption internally

	RSACrypt rsacrypt;

	uint32_t e;
	uint32_t modulus[RAKNET_RSA_FACTOR_LIMBS];

	uint32_t p[RAKNET_RSA_FACTOR_LIMBS/2],q[RAKNET_RSA_FACTOR_LIMBS/2];

	printf("Generating %i bit key. This will take a while...\n", RAKNET_RSA_FACTOR_LIMBS*32);
	rsacrypt.generatePrivateKey(RAKNET_RSA_FACTOR_LIMBS);
	e=rsacrypt.getPublicExponent();
	rsacrypt.getPublicModulus(modulus);
	rsacrypt.getPrivateP(p);
	rsacrypt.getPrivateQ(q);

	RakPeerInterface::DestroyInstance(server);
	server=RakPeerInterface::GetInstance();

	server->InitializeSecurity(0,0,(char*)p, (char*)q);
	server->Startup(1,30,&SocketDescriptor(60000,0),1);
	server->SetMaximumIncomingConnections(1);
	server->SetIncomingPassword(thePassword,strlen(thePassword));

	if (isVerbose)
		printf("Testing if client connects encrypted\n");

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,strlen(thePassword));
		}

		RakSleep(100);

	}

	char str2[]="AAAAAAAAAA";
	str2[0]=(char)(ID_USER_PACKET_ENUM+1);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);

	Packet *packet;
	entryTime=GetTimeMS();
	while(GetTimeMS()-entryTime<1000)
	{
		for (packet=server->Receive(); packet;server->DeallocatePacket(packet), packet=server->Receive())
		{

		}
	}

	RakNetStatistics *rss;

	rss=client->GetStatistics(serverAddress);

	if (rss->encryptionBitsSent<=0)//If we did connect encrypted we should see encryptionBitsSent
	{
		if (isVerbose)
			DebugTools::ShowError("Client did not connect encrypted\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 10;
	}

	while(CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))//disconnect client
	{

		client->CloseConnection (serverAddress,true,0,LOW_PRIORITY); 
	}

	//Destroy to clear statistics
	RakPeerInterface::DestroyInstance(client);

	client=RakPeerInterface::GetInstance();

	client->Startup(1,30,&SocketDescriptor(),1);

	if (isVerbose)
		printf("Testing AddToSecurityExceptionList client should connect without encryption\n");

	server->AddToSecurityExceptionList("127.0.0.1");

	if (!server->IsInSecurityExceptionList("127.0.0.1"))
	{
		if (isVerbose)
			DebugTools::ShowError("IsInSecurityExceptionList does not register localhost addition\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 12;
	}

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,strlen(thePassword));
		}

		RakSleep(100);

	}

	str2[0]=(char)(ID_USER_PACKET_ENUM+1);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);

	//	Packet *packet;

	entryTime=GetTimeMS();
	while(GetTimeMS()-entryTime<1000)
	{
		for (packet=server->Receive(); packet;server->DeallocatePacket(packet), packet=server->Receive())
		{

		}
	}

	rss=client->GetStatistics(serverAddress);

	if (rss->encryptionBitsSent>0)//If we did connect encrypted we should see encryptionBitsSent
	{
		if (isVerbose)
			DebugTools::ShowError("Client connected encrypted but shouldn't have\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 11;
	}

	if (isVerbose)
		printf("Testing RemoveFromSecurityExceptionList\n");

	while(CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))//disconnect client
	{

		client->CloseConnection (serverAddress,true,0,LOW_PRIORITY); 
	}

	server->RemoveFromSecurityExceptionList("127.0.0.1");

	if (isVerbose)
		printf("Testing if client connects encrypted\n");

	entryTime=GetTimeMS();
	while(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true)&&GetTimeMS()-entryTime<5000)
	{

		if(!CommonFunctions::ConnectionStateMatchesOptions (client,serverAddress,true,true,true,true))
		{
			client->Connect("127.0.0.1",serverAddress.port,thePassword,strlen(thePassword));
		}

		RakSleep(100);

	}

	str2[0]=(char)(ID_USER_PACKET_ENUM+1);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);
	client->Send(str2,(int) strlen(str2)+1, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);

	entryTime=GetTimeMS();
	while(GetTimeMS()-entryTime<1000)
	{
		for (packet=server->Receive(); packet;server->DeallocatePacket(packet), packet=server->Receive())
		{

		}
	}

	rss=client->GetStatistics(serverAddress);

	if (rss->encryptionBitsSent<=0)//If we did connect encrypted we should see encryptionBitsSent
	{
		if (isVerbose)
			DebugTools::ShowError("Client did not connect encrypted\n",!noPauses && isVerbose,__LINE__,__FILE__);
		return 10;
	}

*/

	return 0;

}
int ComprehensiveConvertTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	static const int CONNECTIONS_PER_SYSTEM =4;

	SystemAddress currentSystem;

	//	DebugTools::ShowError("Note: The conversion of this is on hold until the original sample's problem is known.",!noPauses && isVerbose,__LINE__,__FILE__);

	//	return 55;

	//	AutoRPC autoRpcs[NUM_PEERS];

	//AutoRPC autoRpcs[NUM_PEERS];

	
	int peerIndex;
	float nextAction;
	int i;
	int portAdd;

	char data[8096];

	int seed = 12345;
	if (isVerbose)
		printf("Using seed %i\n", seed);
	seedMT(seed);

	for (i=0; i < NUM_PEERS; i++)
	{

		//autoRpcs[i].RegisterFunction("RPC1", RPC1, false);
		//autoRpcs[i].RegisterFunction("RPC2", RPC2, false);
		//autoRpcs[i].RegisterFunction("RPC3", RPC3, false);
		//autoRpcs[i].RegisterFunction("RPC4", RPC4, false);
		peers[i]=RakPeerInterface::GetInstance();
		peers[i]->SetMaximumIncomingConnections(CONNECTIONS_PER_SYSTEM);
		SocketDescriptor socketDescriptor(60000+i, 0);
		peers[i]->Startup(NUM_PEERS, &socketDescriptor, 1);
		peers[i]->SetOfflinePingResponse("Offline Ping Data", (int)strlen("Offline Ping Data")+1);

	}

	for (i=0; i < NUM_PEERS; i++)
	{

		portAdd=randomMT()%NUM_PEERS;

		currentSystem.SetBinaryAddress("127.0.0.1");
		currentSystem.port=60000+portAdd;
		if(!CommonFunctions::ConnectionStateMatchesOptions (peers[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
		{
			ConnectionAttemptResult resultReturn = peers[i]->Connect("127.0.0.1", 60000+portAdd, 0, 0);
			if (resultReturn!=CONNECTION_ATTEMPT_STARTED && resultReturn!=ALREADY_CONNECTED_TO_ENDPOINT)
			{
				DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);
				return 1;

			}

		}

	}

	TimeMS endTime = GetTimeMS()+10000;
	while (GetTimeMS()<endTime)
	{
		nextAction = frandomMT();

		if (nextAction < .04f)
		{
			// Initialize
			peerIndex=randomMT()%NUM_PEERS;
			SocketDescriptor socketDescriptor(60000+peerIndex, 0);
			peers[peerIndex]->Startup(NUM_PEERS, &socketDescriptor, 1);
			portAdd=randomMT()%NUM_PEERS;

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000+portAdd;
			
			
			if(!CommonFunctions::ConnectionStateMatchesOptions (peers[peerIndex],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
			{
				ConnectionAttemptResult resultReturn = peers[peerIndex]->Connect("127.0.0.1", 60000+portAdd, 0, 0);
				if (resultReturn!=CONNECTION_ATTEMPT_STARTED && resultReturn!=ALREADY_CONNECTED_TO_ENDPOINT)
				{
					DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					return 1;

				}

			}
		}
		else if (nextAction < .09f)
		{
			// Connect
			peerIndex=randomMT()%NUM_PEERS;
			portAdd=randomMT()%NUM_PEERS;

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000+portAdd;
			if(!CommonFunctions::ConnectionStateMatchesOptions (peers[peerIndex],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
			{
				ConnectionAttemptResult resultReturn = peers[peerIndex]->Connect("127.0.0.1", 60000+portAdd, 0, 0);
				if (resultReturn!=CONNECTION_ATTEMPT_STARTED && resultReturn!=ALREADY_CONNECTED_TO_ENDPOINT)
				{
					DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					return 1;

				}
			}
		}
		else if (nextAction < .10f)
		{
			// Disconnect
			peerIndex=randomMT()%NUM_PEERS;
			//	peers[peerIndex]->Shutdown(randomMT() % 100);
		}
		else if (nextAction < .12f)
		{
			// GetConnectionList
			peerIndex=randomMT()%NUM_PEERS;
			SystemAddress remoteSystems[NUM_PEERS];
			unsigned short numSystems=NUM_PEERS;
			peers[peerIndex]->GetConnectionList(remoteSystems, &numSystems);
			if (numSystems>0)
			{
				if (isVerbose){
					printf("%i: ", 60000+numSystems);
					for (i=0; i < numSystems; i++)
					{
						printf("%i: ", remoteSystems[i].port);
					}
					printf("\n");
				}
			}			
		}
		else if (nextAction < .14f)
		{
			// Send
			int dataLength;
			PacketPriority priority;
			PacketReliability reliability;
			unsigned char orderingChannel;
			SystemAddress target;
			bool broadcast;

			//	data[0]=ID_RESERVED1+(randomMT()%10);
			data[0]=ID_USER_PACKET_ENUM;
			dataLength=3+(randomMT()%8000);
			//			dataLength=600+(randomMT()%7000);
			priority=(PacketPriority)(randomMT()%(int)NUMBER_OF_PRIORITIES);
			reliability=(PacketReliability)(randomMT()%((int)RELIABLE_SEQUENCED+1));
			orderingChannel=randomMT()%32;
			if ((randomMT()%NUM_PEERS)==0)
				target=UNASSIGNED_SYSTEM_ADDRESS;
			else
				target=peers[peerIndex]->GetSystemAddressFromIndex(randomMT()%NUM_PEERS);

			broadcast=(randomMT()%2)>0;
#ifdef _VERIFY_RECIPIENTS
			broadcast=false; // Temporarily in so I can check recipients
#endif

			peerIndex=randomMT()%NUM_PEERS;
			sprintf(data+3, "dataLength=%i priority=%i reliability=%i orderingChannel=%i target=%i broadcast=%i\n", dataLength, priority, reliability, orderingChannel, target.port, broadcast);
			//unsigned short localPort=60000+i;
#ifdef _VERIFY_RECIPIENTS
			memcpy((char*)data+1, (char*)&target.port, sizeof(unsigned short));
#endif
			data[dataLength-1]=0;
			peers[peerIndex]->Send(data, dataLength, priority, reliability, orderingChannel, target, broadcast);
		}
		else if (nextAction < .18f)
		{
			// RPC
			int dataLength;
			PacketPriority priority;
			PacketReliability reliability;
			unsigned char orderingChannel;
			SystemAddress target;
			bool broadcast;
			char RPCName[10];

			data[0]=ID_USER_PACKET_ENUM+(randomMT()%10);
			dataLength=3+(randomMT()%8000);
			//			dataLength=600+(randomMT()%7000);
			priority=(PacketPriority)(randomMT()%(int)NUMBER_OF_PRIORITIES);
			reliability=(PacketReliability)(randomMT()%((int)RELIABLE_SEQUENCED+1));
			orderingChannel=randomMT()%32;
			peerIndex=randomMT()%NUM_PEERS;
			if ((randomMT()%NUM_PEERS)==0)
				target=UNASSIGNED_SYSTEM_ADDRESS;
			else
				target=peers[peerIndex]->GetSystemAddressFromIndex(randomMT()%NUM_PEERS);
			broadcast=(randomMT()%2)>0;
#ifdef _VERIFY_RECIPIENTS
			broadcast=false; // Temporarily in so I can check recipients
#endif

			sprintf(data+3, "dataLength=%i priority=%i reliability=%i orderingChannel=%i target=%i broadcast=%i\n", dataLength, priority, reliability, orderingChannel, target.port, broadcast);
#ifdef _VERIFY_RECIPIENTS
			memcpy((char*)data, (char*)&target.port, sizeof(unsigned short));
#endif
			data[dataLength-1]=0;
			sprintf(RPCName, "RPC%i", (randomMT()%4)+1);
			//				autoRpc[i]->Call(RPCName);
			//peers[peerIndex]->RPC(RPCName, data, dataLength*8, priority, reliability, orderingChannel, target, broadcast, 0, UNASSIGNED_NETWORK_ID,0);
		}
		else if (nextAction < .181f)
		{
			// CloseConnection
			SystemAddress target;
			peerIndex=randomMT()%NUM_PEERS;
			target=peers[peerIndex]->GetSystemAddressFromIndex(randomMT()%NUM_PEERS);
			peers[peerIndex]->CloseConnection(target, (randomMT()%2)>0, 0);
		}
		else if (nextAction < .20f)
		{
			// Offline Ping
			peerIndex=randomMT()%NUM_PEERS;
			peers[peerIndex]->Ping("127.0.0.1", 60000+(randomMT()%NUM_PEERS), (randomMT()%2)>0);
		}
		else if (nextAction < .21f)
		{
			// Online Ping
			SystemAddress target;
			target=peers[peerIndex]->GetSystemAddressFromIndex(randomMT()%NUM_PEERS);
			peerIndex=randomMT()%NUM_PEERS;
			peers[peerIndex]->Ping(target);
		}
		else if (nextAction < .24f)
		{
			// SetCompileFrequencyTable
			peerIndex=randomMT()%NUM_PEERS;
		}
		else if (nextAction < .25f)
		{
			// GetStatistics
			SystemAddress target, mySystemAddress;
			RakNetStatistics *rss;
			mySystemAddress=peers[peerIndex]->GetInternalID();
			target=peers[peerIndex]->GetSystemAddressFromIndex(randomMT()%NUM_PEERS);
			peerIndex=randomMT()%NUM_PEERS;
			rss=peers[peerIndex]->GetStatistics(mySystemAddress);
			if (rss)
			{
				StatisticsToString(rss, data, 0);
				if (isVerbose)
					printf("Statistics for local system %i:\n%s", mySystemAddress.port, data);

			}

			rss=peers[peerIndex]->GetStatistics(target);
			if (rss)
			{
				StatisticsToString(rss, data, 0);
				if (isVerbose)
					printf("Statistics for target system %i:\n%s", target.port, data);

			}			
		}

		for (i=0; i < NUM_PEERS; i++)
			peers[i]->DeallocatePacket(peers[i]->Receive());

		RakSleep(0);

	}

	

	return 0;

}
void NatTypeDetecteUPNPHandler::startCountDown() {
    BaseStageHandler::startCountDown();
    this->timeMileStone = GetTimeMS() + executeMaxTime;
}
int ReliableOrderedConvertedTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *sender, *receiver;
	unsigned int packetNumberSender[32],packetNumberReceiver[32], receivedPacketNumberReceiver, receivedTimeReceiver;
	char str[256];
	char ip[32];
	TimeMS sendInterval, nextSend, currentTime, quitTime;
	unsigned short remotePort, localPort;
	unsigned char streamNumberSender,streamNumberReceiver;
	BitStream bitStream;
	Packet *packet;
	bool doSend=false;

	for (int i=0; i < 32; i++)
	{
		packetNumberSender[i]=0;
		packetNumberReceiver[i]=0;

	}

	/*
	if (argc==2)
	{
	fp = fopen(argv[1],"wt");
	SetMalloc_Ex(LoggedMalloc);
	SetRealloc_Ex(LoggedRealloc);
	SetFree_Ex(LoggedFree);
	}
	else
	*/
	fp=0;
	destroyList.Clear(false,_FILE_AND_LINE_);

	sender =RakPeerInterface::GetInstance();
	destroyList.Push(	sender ,_FILE_AND_LINE_);
	//sender->ApplyNetworkSimulator(.02, 100, 50);

	/*
	if (str[0]==0)
	sendInterval=30;
	else
	sendInterval=atoi(str);*///possible future params

	sendInterval=30;

	/*
	printf("Enter remote IP: ");
	Gets(ip, sizeof(ip));
	if (ip[0]==0)*/
	strcpy(ip, "127.0.0.1");

	/*
	printf("Enter remote port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "60000");
	remotePort=atoi(str);
	/*
	printf("Enter local port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "0");
	localPort=atoi(str);

	if (isVerbose)
		printf("Connecting...\n");

	sender->Startup(1, &SocketDescriptor(localPort,0), 1);
	sender->Connect(ip, remotePort, 0, 0);

	receiver =RakPeerInterface::GetInstance();
	destroyList.Push(	receiver ,_FILE_AND_LINE_);

	/*
	printf("Enter local port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "60000");
	localPort=atoi(str);

	if (isVerbose)
		printf("Waiting for connections...\n");

	receiver->Startup(32, &SocketDescriptor(localPort,0), 1);
	receiver->SetMaximumIncomingConnections(32);

	//	if (sender)
	//		sender->ApplyNetworkSimulator(128000, 50, 100);
	//	if (receiver)
	//		receiver->ApplyNetworkSimulator(128000, 50, 100);

	/*printf("How long to run this test for, in seconds?\n");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "12");

	currentTime = GetTimeMS();
	quitTime = atoi(str) * 1000 + currentTime;

	nextSend=currentTime;

	while (currentTime < quitTime)
		//while (1)
	{

		packet = sender->Receive();
		while (packet)
		{
			// PARSE TYPES
			switch(packet->data[0])
			{
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				doSend=true;
				nextSend=currentTime;
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("Connection attempt failed\n");
				break;
			}

			sender->DeallocatePacket(packet);
			packet = sender->Receive();
		}

		while (doSend && currentTime > nextSend)
		{
			streamNumberSender=0;
			//	streamNumber = randomMT() % 32;
			// Do the send
			bitStream.Reset();
			bitStream.Write((unsigned char) (ID_USER_PACKET_ENUM+1));
			bitStream.Write(packetNumberSender[streamNumberSender]++);
			bitStream.Write(streamNumberSender);
			bitStream.Write(currentTime);
			char *pad;
			int padLength = (randomMT() % 5000) + 1;
			pad = new char [padLength];
			bitStream.Write(pad, padLength);
			delete [] pad;
			// Send on a random priority with a random stream
			// if (sender->Send(&bitStream, HIGH_PRIORITY, (PacketReliability) (RELIABLE + (randomMT() %2)) ,streamNumber, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
			if (sender->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED ,streamNumberSender, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
				packetNumberSender[streamNumberSender]--; // Didn't finish connecting yet?

			RakNetStatistics *rssSender;
			rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));
			if (isVerbose)
				printf("Snd: %i.\n", packetNumberSender[streamNumberSender]);

			nextSend+=sendInterval;

			// Test halting
			//	if (rand()%20==0)
			//		nextSend+=1000;
		}

		packet = receiver->Receive();
		while (packet)
		{
			switch(packet->data[0])
			{
			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_USER_PACKET_ENUM+1:
				bitStream.Reset();
				bitStream.Write((char*)packet->data, packet->length);
				bitStream.IgnoreBits(8); // Ignore ID_USER_PACKET_ENUM+1
				bitStream.Read(receivedPacketNumberReceiver);
				bitStream.Read(streamNumberReceiver);
				bitStream.Read(receivedTimeReceiver);

				if (receivedPacketNumberReceiver!=packetNumberReceiver[streamNumberReceiver])
				{

					//WARNING: If you modify the below code make sure the whole string remains in bounds, sprintf will NOT do it for you. 
					//The error string is 512 in length

					//Note: Removed buffer checking because chance is insignificant, left code if wanted in future. Needs limits.h ISO C standard.

					/*
					int maxIntWorkingCopy= INT_MAX;

					int maxIntCharLen =0; 

					while (maxIntWorkingCopy>0)
					{maxIntCharLen++;
					maxIntWorkingCopy/=10;
					}

					if (strlen(lastError)>maxIntCharLen* 3 +27)//512 should be a good len for now
					{*/

					sprintf(lastError,"Expecting %i got %i (channel %i).",packetNumberReceiver[streamNumberReceiver], receivedPacketNumberReceiver, streamNumberReceiver);

					/*
					}
					else
					{
					sprintf(lastError,"Did not get what was expected. More details can be given if the error string buffer size is increased.");

					}*/

					if (isVerbose)
					{

						RakNetStatistics *rssSender,*rssReceiver;
						char message[2048];

						rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

						rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
						StatisticsToString(rssSender, message, 2);
						printf("Server stats %s\n", message);
						StatisticsToString(rssReceiver, message, 2);
						printf("Client stats%s", message);

						DebugTools::ShowError(lastError,!noPauses && isVerbose,__LINE__,__FILE__);
					}

					return 1;
				}
				else
					if (isVerbose)
					{
						printf("Got %i.Channel %i.Len %i.", packetNumberReceiver[streamNumberReceiver], streamNumberReceiver, packet->length);

						printf("Sent=%u Received=%u Diff=%i.\n", receivedTimeReceiver, currentTime, (int)currentTime - (int) receivedTimeReceiver);
					}

					packetNumberReceiver[streamNumberReceiver]++;
					break;
			}

			receiver->DeallocatePacket(packet);
			packet = receiver->Receive();
		}

		RakSleep(0);

		currentTime=GetTimeMS();
	}

	if (isVerbose)
	{

		RakNetStatistics *rssSender,*rssReceiver;
		char message[2048];

		rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

		rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
		StatisticsToString(rssSender, message, 2);
		printf("Server stats %s\n", message);
		StatisticsToString(rssReceiver, message, 2);
		printf("Client stats%s", message);
	}

	if (fp)
		fclose(fp);

	return 0;
}
/*
What is being done here is having 8 peers all connect to eachother over the max defined connection.

It runs the connect, wait 20 seconds then see the current connections.

Success conditions:
All extra connections Refused.

Failure conditions:
There are more connected than allowed.
The connect function fails, the test is not even done.
GetMaximumIncomingConnections returns wrong value.

RakPeerInterface Functions used, tested indirectly by its use:
Startup
Connect
SetMaximumIncomingConnections
Receive
DeallocatePacket
GetSystemList

RakPeerInterface Functions Explicitly Tested:
SetMaximumIncomingConnections
GetMaximumIncomingConnections 

*/
int MaximumConnectTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	const int peerNum= 8;
	const int maxConnections=4;//Max allowed connections for test
	RakPeerInterface *peerList[peerNum];//A list of 8 peers

	Packet *packet;
	destroyList.Clear(false,_FILE_AND_LINE_);

	int connReturn;
	//Initializations of the arrays
	for (int i=0;i<peerNum;i++)
	{
		peerList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(peerList[i],_FILE_AND_LINE_);

		peerList[i]->Startup(maxConnections, &SocketDescriptor(60000+i,0), 1);
		peerList[i]->SetMaximumIncomingConnections(maxConnections);

		connReturn=peerList[i]->GetMaximumIncomingConnections();
		if (connReturn!=maxConnections)
		{
			if (isVerbose)
			{
				printf("Getmaxconnections wrong for peer %i, %i should be the value but the value is %i.Fail\n",i,maxConnections,connReturn);

				DebugTools::ShowError("",!noPauses && isVerbose,__LINE__,__FILE__);

			}

		}

	}

	//Connect all the peers together

	for (int i=0;i<peerNum;i++)
	{

		for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
		{

			if (peerList[i]->Connect("127.0.0.1", 60000+j, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{

				if (isVerbose)
					DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);

				return 1;//This fails the test, don't bother going on.

			}

		}	

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	while(GetTimeMS()-entryTime<20000)//Run for 20 Secoonds
	{

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{

			packet=peerList[i]->Receive();

			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");//Should happen in this test

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");//Shouldn't happen

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				peerList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	DataStructures::List< SystemAddress  > systemList;
	DataStructures::List< RakNetGUID > guidList;

	for (int i=0;i<peerNum;i++)
	{

		peerList[i]->GetSystemList(systemList,guidList);
		int connNum=guidList.Size();//Get the number of connections for the current peer
		if (connNum>maxConnections)//Did we connect to more?
		{

			if (isVerbose)
			{
				printf("More connections were allowed to peer %i, %i total.Fail\n",i,connNum);

				DebugTools::ShowError("",!noPauses && isVerbose,__LINE__,__FILE__);

			}

			return 2;

		}

	}

	if (isVerbose)
		printf("Pass\n");
	return 0;

}
Beispiel #22
0
/*
What is being done here is having 8 peers all connect to eachother and be
connected. Then it check if they all connect. If so send data in ordered reliable mode for 100
loops.

Possible ideas for changes:
Possibly use rakpeerinterfaces GetSystemList() for number of 
connected peers instead of manually tracking. Would be slower though,
shouldn't be significant at this number but the recieve speed it part of the test.

Success conditions:
Peers connect and receive all packets in order.
No disconnections allowed in this version of the test.

Failure conditions:

If cannot connect to all peers for 20 seconds.
All packets are not recieved.
All packets are not in order.
Disconnection.
*/
int EightPeerTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{
	const int peerNum= 8;
	RakPeerInterface *peerList[peerNum];//A list of 8 peers
	int connectionAmount[peerNum];//Counter for me to keep track of connection requests and accepts
	int recievedFromList[peerNum][peerNum];//Counter for me to keep track of packets received
	int lastNumberReceivedFromList[peerNum][peerNum];//Counter for me to keep track of last recieved sequence number
	const int numPackets=100;
	Packet *packet;
	BitStream bitStream;
	destroyList.Clear(false,_FILE_AND_LINE_);

	//Initializations of the arrays
	for (int i=0;i<peerNum;i++)
	{
		peerList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(peerList[i],_FILE_AND_LINE_);
		connectionAmount[i]=0;

		for (int j=0;j<peerNum;j++)
		{
			recievedFromList[i][j]=0;
			lastNumberReceivedFromList[i][j]=0;
		}

		peerList[i]->Startup(peerNum*2, &SocketDescriptor(60000+i,0), 1);
		peerList[i]->SetMaximumIncomingConnections(peerNum);

	}

	//Connect all the peers together
	for (int i=0;i<peerNum;i++)
	{
		for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
		{
			if (peerList[i]->Connect("127.0.0.1", 60000+j, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{
				if (isVerbose)
				{
					DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

				}
				return 1;//This fails the test, don't bother going on.
			}
		}

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time
	TimeMS finishTimer=GetTimeMS();
	bool initialConnectOver=false;//Our initial connect all has been done.

	for (int k=0;k<numPackets||GetTimeMS()-finishTimer<5000;)//Quit after we send 100 messages while connected, if not all connected and not failure, otherwise fail after 20 seconds and exit
	{
		bool allConnected=true;//Start true, only one failed case makes it all fail
		for (int i=0;i<peerNum;i++)//Make sure all peers are connected to eachother
		{
			if (connectionAmount[i]<peerNum-1)
			{
				allConnected=false;
			}
		}

		if (GetTimeMS()-entryTime>20000 &&!initialConnectOver &&!allConnected)//failed for 20 seconds
		{

			if (isVerbose)
				DebugTools::ShowError("Failed to connect to all peers after 20 seconds",!noPauses && isVerbose,__LINE__,__FILE__);
			return 2;
			break;
		}

		if (allConnected)
		{
			if(!initialConnectOver)
				initialConnectOver=true;
			if (k<numPackets)
			{
			for (int i=0;i<peerNum;i++)//Have all peers send a message to all peers
			{

				bitStream.Reset();

				bitStream.Write((unsigned char) (ID_USER_PACKET_ENUM+1));

				bitStream.Write(k);
				bitStream.Write(i);

				peerList[i]->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);

			}
			}
			k++;
		}

		if (k>=numPackets-3)//This is our last 3 packets, give it time to send packet and arrive on interface, 2 seconds is more than enough 
		{
			RakSleep(300);
			if (k==numPackets)
			{
				finishTimer=GetTimeMS();
			}
		}

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{
			if (allConnected)//If all connected try to make the data more visually appealing by bunching it in one receive
			{
				int waittime=0;
				do
				{
					packet=peerList[i]->Receive();
					waittime++;

					if (!packet)
					{
						RakSleep(1);

					}

					if (waittime>1000)//Check for packet every millisec and if one second has passed move on, don't block execution
					{
						break;
					}
				}
				while(!packet);//For testing purposes wait for packet a little while, go if not recieved
			}
			else//Otherwise just keep recieving quickly until connected
			{
				packet=peerList[i]->Receive();
			}
			if (isVerbose)
				printf("For peer %i with %i connected peers.\n",i,connectionAmount[i]);
			while(packet)
			{
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
					{
						printf("Another client has disconnected.\n");
						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 3;
					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
					{
						printf("Another client has lost the connection.\n");
						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);           
					}
					return 3;
					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");
					connectionAmount[i]++;

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:

					if (isVerbose)
						DebugTools::ShowError("A connection has failed.\n Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					return 2;
					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");
					connectionAmount[i]++;//For this test assume connection. Test will fail if connection fails.
					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS://Should not happend
					if (isVerbose)    
					{
						printf("The server is full. This shouldn't happen in this test ever.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 2;
					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");//Shouldn't happen

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
					{
						printf("We have been disconnected.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 3;
					break;
				case ID_CONNECTION_LOST:
					allConnected=false;
					connectionAmount[i]--;
					if (isVerbose)
					{
						printf("Connection lost.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}

					return 3;

					break;
				default:

					if (packet->data[0]==ID_USER_PACKET_ENUM+1)
					{
						int thePeerNum;
						int sequenceNum;
						bitStream.Reset();
						bitStream.Write((char*)packet->data, packet->length);
						bitStream.IgnoreBits(8);
						bitStream.Read(sequenceNum);
						bitStream.Read(thePeerNum);
						if (isVerbose)
							printf("Message %i from %i\n",sequenceNum,thePeerNum );

						if (thePeerNum>=0&&thePeerNum<peerNum)
						{
							if (lastNumberReceivedFromList[i][thePeerNum]==sequenceNum)
							{
								lastNumberReceivedFromList[i][thePeerNum]++;
							}
							else
							{
								if (isVerbose)
								{
									printf("Packets out of order");
									DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);

								}
								return 4;
							}
							recievedFromList[i][thePeerNum]++;}
					}
					break;
				}
				peerList[i]->DeallocatePacket(packet);
				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	for (int i=0;i<peerNum;i++)
	{

		for (int j=0;j<peerNum;j++)
		{
			if (i!=j)
			{
				if (isVerbose)
					printf("%i recieved %i packets from %i\n",i,recievedFromList[i][j],j);
				if  (recievedFromList[i][j]!=numPackets)
				{
					if (isVerbose)
					{
						printf("Not all packets recieved. it was in reliable ordered mode so that means test failed or wait time needs increasing\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 5;

				}

			}
		}
	}

	printf("All packets recieved in order,pass\n");
	return 0;

}
void NatPunchThroughHandler::startCountDown() {
    BaseStageHandler::startCountDown();
    this->timeMileStone = GetTimeMS() + 100000;
}
Beispiel #24
0
int PingTestsTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *sender,*sender2, *receiver;
	destroyList.Clear(false,_FILE_AND_LINE_);

	TestHelpers::StandardClientPrep(sender,destroyList);

	TestHelpers::StandardClientPrep(sender2,destroyList);

	receiver=RakPeerInterface::GetInstance();
	destroyList.Push(receiver,_FILE_AND_LINE_);
	receiver->Startup(2, &SocketDescriptor(60000,0), 1);
	receiver->SetMaximumIncomingConnections(2);
	Packet * packet;

	SystemAddress currentSystem;

	currentSystem.SetBinaryAddress("127.0.0.1");
	currentSystem.port=60000;

	printf("Connecting sender2\n");
	if (!TestHelpers::WaitAndConnectTwoPeersLocally(sender2,receiver,5000))
	{

		if (isVerbose)
			DebugTools::ShowError("Could not connect after 5 seconds\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 2;

	}

	printf("Getting ping data for lastping and lowestping\n");
	sender2->SetOccasionalPing(false);//Test the lowest ping and such without  occassionalping,occasional ping comes later
	RakTimer timer(1500);

	int lastPing=0;
	int lowestPing=0;
	TimeMS nextPing=0;

	while(!timer.IsExpired())
	{
		for (packet=receiver->Receive();packet;receiver->DeallocatePacket(packet),packet=receiver->Receive())
		{
			if (isVerbose)
				printf("Receive packet id %i\n",packet->data[0]);
		}

		for (packet=sender2->Receive();packet;sender2->DeallocatePacket(packet),packet=sender2->Receive())
		{
			if (isVerbose)
				printf("Send packet id %i\n",packet->data[0]);

		}

		if (GetTimeMS()>nextPing)
		{
			sender2->Ping(currentSystem);
			nextPing=GetTimeMS()+30;
		}

		RakSleep(3);
	}

	int averagePing=sender2->GetAveragePing(currentSystem);
	if (isVerbose)
		printf("Average Ping time %i\n",averagePing);

	lastPing=sender2->GetLastPing(currentSystem);
	lowestPing=sender2->GetLowestPing(currentSystem);

	if (isVerbose)
		printf("Last Ping time %i\n",lastPing);

	if (isVerbose)
		printf("Lowest Ping time %i\n",lowestPing);

	int returnVal=TestAverageValue(averagePing,__LINE__, noPauses, isVerbose);

	if (returnVal!=0)
	{

		return returnVal;
	}

	if (lastPing>100)//100 MS for localhost?
	{
		if (isVerbose)
			DebugTools::ShowError("Problem with the last ping time,greater then 100MS for localhost\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 3;
	}

	if (lowestPing>10)//The lowest ping for localhost should drop below 10MS at least once
	{

		if (isVerbose)
			DebugTools::ShowError("The lowest ping for localhost should drop below 10MS at least once\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 4;
	}

	if (lastPing<lowestPing)
	{

		if (isVerbose)
			DebugTools::ShowError("There is a problem if the lastping is lower than the lowestping stat\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 5;
	}

	CommonFunctions::DisconnectAndWait(sender2,"127.0.0.1",60000);//Eliminate variables.

	printf("Connecting sender\n");
	if (!TestHelpers::WaitAndConnectTwoPeersLocally(sender,receiver,5000))
	{

		if (isVerbose)
			DebugTools::ShowError("Could not connect after 5 seconds\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 2;

	}

	lastPing=0;
	lowestPing=0;
	sender->SetOccasionalPing(true);

	printf("Testing SetOccasionalPing\n");

	timer.Start();
	while(!timer.IsExpired())
	{
		for (packet=receiver->Receive();packet;receiver->DeallocatePacket(packet),packet=receiver->Receive())
		{
			if (isVerbose)
				printf("Receive packet id %i\n",packet->data[0]);
		}

		for (packet=sender->Receive();packet;sender->DeallocatePacket(packet),packet=sender->Receive())
		{
			if (isVerbose)
				printf("Send packet id %i\n",packet->data[0]);

		}

		RakSleep(3);
	}

	averagePing=sender->GetAveragePing(currentSystem);
	if (isVerbose)
		printf("Average Ping time %i\n",averagePing);

	returnVal=TestAverageValue(averagePing,__LINE__, noPauses, isVerbose);

	if (returnVal!=0)
	{

		return returnVal;
	}

	return 0;

}
/*
What is being done here is having 256 clients connect to one server, disconnect, connect again.

Do this for about 10 seconds. Then allow them all to connect for one last time.

This one has a nonblocking recieve so doesn't wait for connects or anything.
Just rapid connecting disconnecting.

Good ideas for changes:
After the last check run a eightpeers like test an add the conditions
of that test as well.

Make sure that if we initiate the connection we get a proper message
and if not we get a proper message. Add proper conditions.

Randomize sending the disconnect notes

Success conditions:
All connected normally.

Failure conditions:
Doesn't reconnect normally.

During the very first connect loop any connect returns false.

Connect function returns false and peer is not connected to anything.

*/
int ManyClientsOneServerNonBlockingTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	const int clientNum= 256;

	RakPeerInterface *clientList[clientNum];//A list of clients
	RakPeerInterface *server;//The server
	SystemAddress currentSystem;

	//SystemAddress currentSystem;

	Packet *packet;
	destroyList.Clear(false,_FILE_AND_LINE_);

	//Initializations of the arrays
	for (int i=0;i<clientNum;i++)
	{
		clientList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(clientList[i],_FILE_AND_LINE_);

		clientList[i]->Startup(1,&SocketDescriptor(), 1);

	}

	server=RakPeerInterface::GetInstance();
	destroyList.Push(server,_FILE_AND_LINE_);
	server->Startup(clientNum, &SocketDescriptor(60000,0), 1);
	server->SetMaximumIncomingConnections(clientNum);

	//Connect all the clients to the server

	for (int i=0;i<clientNum;i++)
	{

		if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
		{

			if (isVerbose)
				DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);

			return 1;//This fails the test, don't bother going on.

		}

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	DataStructures::List< SystemAddress  > systemList;
	DataStructures::List< RakNetGUID > guidList;

	if (isVerbose)
		printf("Entering disconnect loop \n");

	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		//Disconnect all clients IF connected to any from client side
		for (int i=0;i<clientNum;i++)
		{

			clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
			int len=systemList.Size();

			for (int j=0;j<len;j++)//Disconnect them all
			{

				clientList[i]->CloseConnection (systemList[j],true,0,LOW_PRIORITY); 	
			}

		}

		//RakSleep(100);

		//Connect

		for (int i=0;i<clientNum;i++)
		{

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000;
			if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
			{

				if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
				{

					if (isVerbose)
						DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

					return 1;//This fails the test, don't bother going on.

				}
			}

		}

		//Server receive

		packet=server->Receive();

		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)              
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)              
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)              
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all peers
		{

			packet=clientList[i]->Receive();

			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	entryTime=GetTimeMS();

	while(GetTimeMS()-entryTime<2000)//Run for 2 Secoonds to process incoming disconnects
	{

		//Server receive

		packet=server->Receive();

		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)              
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)              
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)              
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all peers
		{

			packet=clientList[i]->Receive();
			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	//Connect

	for (int i=0;i<clientNum;i++)
	{

		currentSystem.SetBinaryAddress("127.0.0.1");
		currentSystem.port=60000;

		if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
		{

			if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{

				clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
				int len=systemList.Size();

				if (isVerbose)
					DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

				return 1;//This fails the test, don't bother going on.

			}
		}

	}

	entryTime=GetTimeMS();

	while(GetTimeMS()-entryTime<5000)//Run for 5 Secoonds
	{

		//Server receive

		packet=server->Receive();
		if (isVerbose&&packet)
			printf("For server\n");

		while(packet)
		{

			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("Another client has disconnected.\n");

				break;
			case ID_REMOTE_CONNECTION_LOST:
				if (isVerbose)
					printf("Another client has lost the connection.\n");

				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)              
					printf("Our connection request has been accepted.\n");

				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("A connection has failed.\n");

				break;

			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)              
					printf("A connection is incoming.\n");

				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)              
					printf("The server is full.\n");

				break;

			case ID_ALREADY_CONNECTED:
				if (isVerbose)              
					printf("Already connected\n");

				break;

			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("We have been disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("Connection lost.\n");

				break;
			default:

				break;
			}

			server->DeallocatePacket(packet);

			// Stay in the loop as long as there are more packets.
			packet = server->Receive();
		}

		for (int i=0;i<clientNum;i++)//Receive for all clients
		{

			packet=clientList[i]->Receive();
			if (isVerbose&&packet)
				printf("For peer %i\n",i);

			while(packet)
			{

				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				clientList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = clientList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	for (int i=0;i<clientNum;i++)
	{

		clientList[i]->GetSystemList(systemList,guidList);
		int connNum=guidList.Size();//Get the number of connections for the current peer
		if (connNum!=1)//Did we connect to all?
		{

			if (isVerbose)
				printf("Not all clients reconnected normally.\nFailed on clients number %i\n",i);

			if (isVerbose)
				DebugTools::ShowError("",!noPauses && isVerbose,__LINE__,__FILE__);

		
			

			return 2;

		}

	}

	

	if (isVerbose)
		printf("Pass\n");
	return 0;

}
Beispiel #26
0
	float GTTime::GetRealTimeSinceStartup()
	{
		long long time = GetTimeMS() - m_time_startup;

		return time / 1000.0f;
	}
/*
What is being done here is having 8 peers all connect to eachother, disconnect, connect again.

Do this for about 10 seconds. Then allow them all to connect for one last time.

This test also tests the cancelpendingconnections.

Also tests nonblocking connects, the simpler one PeerConnectDisconnect tests without it

Good ideas for changes:
After the last check run a eightpeers like test an add the conditions
of that test as well.

Make sure that if we initiate the connection we get a proper message
and if not we get a proper message. Add proper conditions.

Randomize sending the disconnect notes

Success conditions:
All connected normally and pending requests get canceled normally.

Failure conditions:
Doesn't reconnect normally.

During the very first connect loop any connect returns false.

Connect function returns false and peer is not connected to anything.

Pending request is not canceled.

*/
int PeerConnectDisconnectWithCancelPendingTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	const int peerNum= 8;
	const int maxConnections=peerNum*3;//Max allowed connections for test set to times 3 to eliminate problem variables
	RakPeerInterface *peerList[peerNum];//A list of 8 peers

	SystemAddress currentSystem;

	Packet *packet;
	destroyList.Clear(false,_FILE_AND_LINE_);

	//Initializations of the arrays
	for (int i=0;i<peerNum;i++)
	{
		peerList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(peerList[i],_FILE_AND_LINE_);

		peerList[i]->Startup(maxConnections, &SocketDescriptor(60000+i,0), 1);
		peerList[i]->SetMaximumIncomingConnections(maxConnections);

	}

	//Connect all the peers together

	for (int i=0;i<peerNum;i++)
	{

		for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
		{

			if (peerList[i]->Connect("127.0.0.1", 60000+j, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{

				if (isVerbose)
					DebugTools::ShowError("Problem while calling connect.",!noPauses && isVerbose,__LINE__,__FILE__);

				return 1;//This fails the test, don't bother going on.

			}

		}	

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	DataStructures::List< SystemAddress  > systemList;
	DataStructures::List< RakNetGUID > guidList;

	printf("Entering disconnect loop \n");
	bool printedYet;

	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		//Disconnect all peers IF connected to any
		for (int i=0;i<peerNum;i++)
		{

			peerList[i]->GetSystemList(systemList,guidList);//Get connectionlist
			int len=systemList.Size();

			for (int j=0;j<len;j++)//Disconnect them all
			{

				peerList[i]->CloseConnection (systemList[j],true,0,LOW_PRIORITY); 	
			}

		}

		RakSleep(100);
		//Clear pending if not finished

		for (int i=0;i<peerNum;i++)
		{

			for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
			{

				currentSystem.SetBinaryAddress("127.0.0.1");
				currentSystem.port=60000+j;

				peerList[i]->CancelConnectionAttempt(currentSystem);  	//Make sure a connection is not pending before trying to connect.

			}

		}

		RakSleep(100);
		//Connect

		for (int i=0;i<peerNum;i++)
		{

			for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
			{

				if (peerList[i]->Connect("127.0.0.1", 60000+j, 0,0)!=CONNECTION_ATTEMPT_STARTED)
				{

					currentSystem.SetBinaryAddress("127.0.0.1");
					currentSystem.port=60000+j;

					peerList[i]->GetSystemList(systemList,guidList);//Get connectionlist

					int len=systemList.Size();

					if(CommonFunctions::ConnectionStateMatchesOptions (peerList[i],currentSystem,false,true,true))//Did we drop the pending connection? 
					{
						if (isVerbose)
							DebugTools::ShowError("Did not cancel the pending request \n",!noPauses && isVerbose,__LINE__,__FILE__);

						return 3;

					}

					if (!CommonFunctions::ConnectionStateMatchesOptions (peerList[i],currentSystem,true,true,true,true))
					{
						if (isVerbose)
							DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

						return 1;//This fails the test, don't bother going on.
					}

				}

			}	

		}

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{

			printedYet=false;

			packet=peerList[i]->Receive();

			while(packet)
			{

				if (isVerbose&&!printedYet)
				{
					printf("For peer %i\n",i);
					printedYet=true;
				}
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				peerList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	while(GetTimeMS()-entryTime<2000)//Run for 2 Secoonds to process incoming disconnects
	{

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{
			printedYet=false;

			packet=peerList[i]->Receive();

			while(packet)
			{

				if (isVerbose&&!printedYet)
				{
					printf("For peer %i\n",i);
					printedYet=true;
				}
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				peerList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	//Connect

	for (int i=0;i<peerNum;i++)
	{

		for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
		{

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000+j;

			peerList[i]->CancelConnectionAttempt(currentSystem);  	//Make sure a connection is not pending before trying to connect.

			if (peerList[i]->Connect("127.0.0.1", 60000+j, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{

				peerList[i]->GetSystemList(systemList,guidList);//Get connectionlist
				int len=systemList.Size();

				if (len==0)//No connections, should not fail.
				{

					if (isVerbose)
						DebugTools::ShowError("Problem while calling connect \n",!noPauses && isVerbose,__LINE__,__FILE__);

					return 1;//This fails the test, don't bother going on.
				}

			}

		}	

	}

	entryTime=GetTimeMS();

	while(GetTimeMS()-entryTime<5000)//Run for 5 Secoonds
	{

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{

			printedYet=false;
			packet=peerList[i]->Receive();

			while(packet)
			{
				if (isVerbose&&!printedYet)
				{
					printf("For peer %i\n",i);
					printedYet=true;
				}
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("Another client has disconnected.\n");

					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
						printf("Another client has lost the connection.\n");

					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:
					if (isVerbose)
						printf("A connection has failed.\n");

					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");

					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					if (isVerbose)              
						printf("The server is full.\n");

					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");

					break;

				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
						printf("We have been disconnected.\n");
					break;
				case ID_CONNECTION_LOST:
					if (isVerbose)
						printf("Connection lost.\n");

					break;
				default:

					break;
				}

				peerList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}

	for (int i=0;i<peerNum;i++)
	{

		peerList[i]->GetSystemList(systemList,guidList);
		int connNum=guidList.Size();//Get the number of connections for the current peer
		if (connNum!=peerNum-1)//Did we connect to all?
		{

			if (isVerbose)
				DebugTools::ShowError("Not all peers reconnected normally.\n ",!noPauses && isVerbose,__LINE__,__FILE__);

			return 2;

		}

	}

	if (isVerbose)
		printf("Pass\n");
	return 0;

}
Beispiel #28
0
int main(int argc, char** argv)
{
    //Matrix4x4f mat = Matrix4x4f::PerspectiveProjection(90, 0.1, 100, 1.f/1.f);
    //assert((mat * Matrix4x4f()) == mat); //works :)

    if(1) //actual game
    {
        WAAF level;
        if(!level.LoadFromFile("../data/level1.waa"))
        {
            std::cerr<<"Could not load data/level1.waa"<<std::endl;
            system("pause");
            return 0;
        }
        Player player;
        player.position = level.GetPlayerPos();

        //    Physics Setup

        //collision configuration contains default setup for memory, collision setup
        btDefaultCollisionConfiguration collisionConfiguration;
        //use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
        btCollisionDispatcher collisionDispatcher(&collisionConfiguration);
        btDbvtBroadphase broadphase;
        //the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
        btSequentialImpulseConstraintSolver solver;
        //create physics world
        btDiscreteDynamicsWorld physicsWorld(&collisionDispatcher, &broadphase, &solver, &collisionConfiguration);

        //stuff copied from bullet samples
        physicsWorld.getSolverInfo().m_splitImpulse=true;
        physicsWorld.getSolverInfo().m_numIterations = 20;
        //set gravity
        physicsWorld.setGravity(btVector3(0,-10,0));

        btRigidBody levelBody(btRigidBody::btRigidBodyConstructionInfo(0.f, NULL, level.GetPhysMesh()));
        physicsWorld.addRigidBody(&levelBody);

        btRigidBody::btRigidBodyConstructionInfo playerBodyInfo(10.f, NULL, &player.physShape);
        playerBodyInfo.m_startWorldTransform.setOrigin(btVector3(player.position.X, player.position.Y, player.position.Z));
        btRigidBody playerBody(playerBodyInfo);
        physicsWorld.addRigidBody(&playerBody);

        //    Console Setup

        if(!Console::Init())
        {
            std::cerr<<"Could not initialize console!"<<std::endl;
            system("pause");
            return 0;
        }

        //    Renderer Setup

        static const float FOV = 90;
        static const float NEAR_CLIP = .1f;
        static const float FAR_CLIP = 100.f;
        AsciiRenderer renderer;
        {
            float width = Console::GetWidth();
            float height = Console::GetHeight() - 1; //cannot use last line due to end-of-line cursor wrap
            if(!renderer.Init(width, height, FOV, NEAR_CLIP, FAR_CLIP))
            {
                std::cerr<<"Could not initialize renderer!"<<std::endl;
                Console::Destroy();
                system("pause");
                return 0;
            }
        }

        //    Main Loop

        renderer.ApplyModelviewMatrix(Matrix4x4f::Translation(level.GetPlayerPos()));

        bool running = true; //the game, not the player (I lost the game -.-)
        //movement keys
        bool moveForward = false;
        bool moveLeft = false;
        bool moveRight = false;
        bool moveBack = false;
        bool moveUp = false; //aka jump
        bool menu = true;
        ShowMenu(); //initial render
        unsigned long long lastFrameTime = GetTimeMS();
        float pitch = 0.f; //in rad
        float yaw = 0.f;
        float mouseScaleX = .05f / 180.f * 3.1415f;
        float mouseScaleY = -.05f / 180.f * 3.1415f;
        float movespeed = 1.f;

        while(running)
        {
            MouseMoveEvent mouseMove;
            mouseMove.X = 0;
            mouseMove.Y = 0;
            //    Event Loop
            Event ev;
            while(Console::PollEvent(ev))
            {
                switch(ev.Type)
                {
                case KeyPressed:
                {
                    switch(ev.Key.Code)
                    {
                    case KEYCODE_ESCAPE: // quit on escape pressed
                    {
                        if(menu)
                        {
                            running = false;
                        }
                        else
                        {
                            menu = true;
                            ShowMenu();
                        }
                        break;
                    }
                    case KEYCODE_RETURN:
                    {
                        menu = false;
                        break;
                    }
                    case KEYCODE_W:
                    {
                        moveForward = true;
                        break;
                    }
                    case KEYCODE_A:
                    {
                        moveLeft = true;
                        break;
                    }
                    case KEYCODE_S:
                    {
                        moveBack = true;
                        break;
                    }
                    case KEYCODE_D:
                    {
                        moveRight = true;
                        break;
                    }
                    case KEYCODE_SPACE:
                    {
                        moveUp = true;
                        break;
                    }
                    default:
                    {
                        break;
                    }
                    }
                    break;
                }
                case KeyReleased:
                {
                    switch(ev.Key.Code)
                    {
                    case KEYCODE_W:
                    {
                        moveForward = false;
                        break;
                    }
                    case KEYCODE_A:
                    {
                        moveLeft = false;
                        break;
                    }
                    case KEYCODE_S:
                    {
                        moveBack = false;
                        break;
                    }
                    case KEYCODE_D:
                    {
                        moveRight = false;
                        break;
                    }
                    default:
                    {
                        break;
                    }
                    }
                    break;
                }
                case Resized: // change resolution when window resized
                {
                    if(!renderer.Init(ev.Resize.SizeX, ev.Resize.SizeY - 1, FOV, NEAR_CLIP, FAR_CLIP))
                    {
                        std::cerr << "Could not change resolution!" << std::endl;
                        Console::Destroy();
                        system("pause");
                        return 0;
                    }
                    break;
                }
                case MouseMoved:
                {
                    mouseMove = ev.MouseMove;
                    break;
                }
                case MouseButtonPressed:
                {
                    break;
                }
                case MouseButtonReleased:
                {
                    break;
                }
                case MouseWheelMoved:
                {
                    break;
                }
                default:
                {
                    break;
                }
                }
            } //end event loop

            //    Game Logic
            unsigned long long frameTime = GetTimeMS();
            unsigned int deltaT = frameTime - lastFrameTime;
            lastFrameTime = frameTime;

            if(menu)
            {
                //no logic required in menu, just await events
            }
            else
            {
                yaw += mouseMove.X * mouseScaleX;
                pitch += mouseMove.Y * mouseScaleY;
                while(yaw > 360.f/ 180.f * 3.1415f) yaw -= 360.f/ 180.f * 3.1415f;
                while(yaw < 0.f) yaw += 360.f;
                //clip pitch to [-90°, 90°]
                if(pitch < -3.1415f/2.f) pitch = -3.1415f/2.f;
                if(pitch > 3.1415f/2.f) pitch = 3.1415f/2.f;

                //  move mouse cursor back to 100, 100 and queue mouse moves
                Console::Update();
                if(deltaT > 0)
                {
                    physicsWorld.stepSimulation(deltaT); //should ideally be fixed - cba
                    //todo: updating goes here
                }

                btVector3 moveDir = CalculateMoveDir(moveLeft, moveForward, moveRight, moveBack, yaw);
                moveDir = moveDir * deltaT * movespeed;
                //playerBody.applyCentralForce(moveDir);
            }

            //    Rendering
            if(menu)
            {
                //menu is fixed, no rendering required
                Sleep(5);
            }
            else
            {
                Matrix4x4f posMat;
                posMat._14 = -playerBody.getWorldTransform().getOrigin().x();
                posMat._24 = -playerBody.getWorldTransform().getOrigin().y();
                posMat._34 = -playerBody.getWorldTransform().getOrigin().z();
                renderer.SetModelviewMatrix(Matrix4x4f());
                renderer.ApplyModelviewMatrix(Matrix4x4f::SimpleRotation(pitch , yaw));
                renderer.ApplyModelviewMatrix(posMat);
                // clear
                renderer.ClearDepth();
                renderer.ClearColor();
                // render
                level.Render(renderer);
                // "switch buffers"
                std::stringstream ss;
                char const * const * const colBuf = renderer.GetColorBuffer();
                for(unsigned int y = 0; y < renderer.GetHeight(); ++y)
                {
                    ss << std::string(colBuf[y], renderer.GetWidth());// << "\n"; //if width is not correct
                }
                Console::GotoXY(0, 0);
                Console::Write(ss.str());
            }
        }

        Console::Destroy();

        return 0;
    }
}
/*
What is being done here is having 256 clients connect to a server, disconnect, connect again.

Do this for about 10 seconds. Then allow them all to connect for one last time.

This version waits for connect and such in a loop, blocking execution so it is a blocking test.

Good ideas for changes:
After the last check run a eightpeers like test an add the conditions
of that test as well.

Make sure that if we initiate the connection we get a proper message
and if not we get a proper message. Add proper conditions.

Randomize sending the disconnect notes

Success conditions:
All connected normally.

Failure conditions:
Doesn't reconnect normally.

During the very first connect loop any connect returns false.

Connect function returns false and peer is not connected to anything and does not have anything pending.

*/
int ManyClientsOneServerBlockingTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	const int clientNum= 256;

	RakPeerInterface *clientList[clientNum];//A list of clients
	RakPeerInterface *server;

	SystemAddress currentSystem;

	destroyList.Clear(false,_FILE_AND_LINE_);

	//Initializations of the arrays
	for (int i=0;i<clientNum;i++)
	{

		clientList[i]=RakPeerInterface::GetInstance();
		destroyList.Push(clientList[i],_FILE_AND_LINE_);

		clientList[i]->Startup(1,&SocketDescriptor(), 1);

	}

	server=RakPeerInterface::GetInstance();
	destroyList.Push(server,_FILE_AND_LINE_);
	server->Startup(clientNum, &SocketDescriptor(60000,0), 1);
	server->SetMaximumIncomingConnections(clientNum);

	//Connect all the clients to the server

	for (int i=0;i<clientNum;i++)
	{

		if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
		{

			if (isVerbose)
				DebugTools::ShowError("Problem while calling connect.\n",!noPauses && isVerbose,__LINE__,__FILE__);

			return 1;//This fails the test, don't bother going on.

		}

	}

	TimeMS entryTime=GetTimeMS();//Loop entry time

	DataStructures::List< SystemAddress  > systemList;
	DataStructures::List< RakNetGUID > guidList;

	printf("Entering disconnect loop \n");

	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		//Disconnect all clients IF connected to any from client side
		for (int i=0;i<clientNum;i++)
		{

			clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
			int len=systemList.Size();

			for (int j=0;j<len;j++)//Disconnect them all
			{

				clientList[i]->CloseConnection (systemList[j],true,0,LOW_PRIORITY); 	
			}

		}

		RakSleep(100);

		//Connect

		for (int i=0;i<clientNum;i++)
		{

			currentSystem.SetBinaryAddress("127.0.0.1");
			currentSystem.port=60000;
			if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
			{

				if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
				{

					if (isVerbose)
						DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

					return 1;//This fails the test, don't bother going on.

				}
			}

		}

		WaitAndPrintResults(clientList,clientNum,isVerbose,server);

	}

	WaitAndPrintResults(clientList,clientNum,isVerbose,server);

	printf("Connecting clients\n");

	//Connect

	for (int i=0;i<clientNum;i++)
	{

		currentSystem.SetBinaryAddress("127.0.0.1");
		currentSystem.port=60000;

		if(!CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true,true,true,true) )//Are we connected or is there a pending operation ?
		{
			printf("Calling Connect() for client %i.\n",i);

			if (clientList[i]->Connect("127.0.0.1", 60000, 0,0)!=CONNECTION_ATTEMPT_STARTED)
			{
				clientList[i]->GetSystemList(systemList,guidList);//Get connectionlist
				int len=systemList.Size();

				if (isVerbose)
					DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

				return 1;//This fails the test, don't bother going on.

			}
		}
		else
		{
			if (CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,false,false,false,true)==false)
				printf("Not calling Connect() for client %i because it is disconnecting.\n",i);
			else if (CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,false,true,true)==false)
				printf("Not calling Connect() for client %i  because it is connecting.\n",i);
			else if (CommonFunctions::ConnectionStateMatchesOptions (clientList[i],currentSystem,true)==false)
				printf("Not calling Connect() for client %i because it is connected).\n",i);
		}

	}

	WaitAndPrintResults(clientList,clientNum,isVerbose,server);

	for (int i=0;i<clientNum;i++)
	{

		clientList[i]->GetSystemList(systemList,guidList);
		int connNum=guidList.Size();//Get the number of connections for the current peer
		if (connNum!=1)//Did we connect all?
		{

			if (isVerbose)
			{
				printf("Not all clients reconnected normally.\nFailed on client number %i\n",i);

				DebugTools::ShowError("",!noPauses && isVerbose,__LINE__,__FILE__);
			}
	
			

			return 2;

		}

	}

	

	if (isVerbose)
		printf("Pass\n");
	return 0;

}