1 #include "CommonFunctions.h"
2 
CommonFunctions(void)3 CommonFunctions::CommonFunctions(void)
4 {
5 }
6 
~CommonFunctions(void)7 CommonFunctions::~CommonFunctions(void)
8 {
9 }
10 
WaitAndConnect(RakPeerInterface * peer,char * ip,unsigned short int port,int millisecondsToWait)11 bool CommonFunctions::WaitAndConnect(RakPeerInterface *peer,char* ip,unsigned short int port,int millisecondsToWait)
12 {
13 
14 	SystemAddress connectToAddress;
15 
16 	connectToAddress.SetBinaryAddress(ip);
17 	connectToAddress.port=port;
18 	RakNetTime entryTime=RakNet::GetTime();
19 
20 	while(!peer->IsConnected (connectToAddress,false,false)&&RakNet::GetTime()-entryTime<millisecondsToWait)
21 	{
22 
23 		if(!peer->IsConnected (connectToAddress,true,true))
24 		{
25 			peer->Connect(ip,port,0,0);
26 		}
27 
28 		RakSleep(100);
29 
30 	}
31 
32 	if (peer->IsConnected (connectToAddress,false,false))
33 	{
34 		return 1;
35 	}
36 
37 	return 0;
38 }
39 
DisconnectAndWait(RakPeerInterface * peer,char * ip,unsigned short int port)40 void CommonFunctions::DisconnectAndWait(RakPeerInterface *peer,char* ip,unsigned short int port)
41 {
42 	SystemAddress targetAddress;
43 
44 	targetAddress.SetBinaryAddress(ip);
45 	targetAddress.port=port;
46 
47 	while(peer->IsConnected (targetAddress,true,true))//disconnect client
48 	{
49 
50 		peer->CloseConnection (targetAddress,true,0,LOW_PRIORITY);
51 	}
52 
53 }
54 
WaitForMessageWithID(RakPeerInterface * reciever,int id,int millisecondsToWait)55 bool CommonFunctions::WaitForMessageWithID(RakPeerInterface *reciever,int id,int millisecondsToWait)
56 {
57 
58 	RakTimer timer(millisecondsToWait);
59 
60 	Packet *packet;
61 	while(!timer.IsExpired())
62 	{
63 		for (packet=reciever->Receive(); packet;reciever->DeallocatePacket(packet), packet=reciever->Receive())
64 		{
65 
66 			//printf("Packet %i\n",packet->data[0]);
67 			if (packet->data[0]==id)
68 			{
69 				reciever->DeallocatePacket(packet);
70 				return true;
71 			}
72 
73 		}
74 
75 	}
76 
77 	return false;
78 }
79 
WaitAndReturnMessageWithID(RakPeerInterface * reciever,int id,int millisecondsToWait)80 Packet *CommonFunctions::WaitAndReturnMessageWithID(RakPeerInterface *reciever,int id,int millisecondsToWait)
81 {
82 
83 	RakTimer timer(millisecondsToWait);
84 
85 	Packet *packet;
86 	while(!timer.IsExpired())
87 	{
88 		for (packet=reciever->Receive(); packet;reciever->DeallocatePacket(packet), packet=reciever->Receive())
89 		{
90 
91 		//	printf("Packet %i\n",packet->data[0]);
92 			if (packet->data[0]==id)
93 			{
94 				return packet;
95 			}
96 
97 		}
98 
99 	}
100 
101 	return 0;
102 }