本文整理汇总了C++中raknet::BitStream::Reset方法的典型用法代码示例。如果您正苦于以下问题:C++ BitStream::Reset方法的具体用法?C++ BitStream::Reset怎么用?C++ BitStream::Reset使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类raknet::BitStream
的用法示例。
在下文中一共展示了BitStream::Reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Destruct
void ReplicaManager::Destruct(Replica *replica, PlayerID playerId, bool broadcast)
{
assert(replica);
bool objectExists;
unsigned replicatedObjectsIndex;
replicatedObjectsIndex = replicatedObjects.GetIndexFromKey(replica, &objectExists);
if (objectExists==false)
return;
// For each existing participant, send a packet telling them of this object destruction
RakNet::BitStream outBitstream;
unsigned i,tempIndex;
bool replicaReferenced;
ParticipantStruct *participantStruct;
replicaReferenced=false;
for (i=0; i < participantList.Size(); i++)
{
participantStruct=participantList[i];
if ((broadcast==true && playerId!=participantStruct->playerId) ||
(broadcast==false && playerId==participantStruct->playerId))
{
// Send the destruction packet immediately
if (replica->GetNetworkID()!=UNASSIGNED_NETWORK_ID && (replicatedObjects[replicatedObjectsIndex].allowedInterfaces & REPLICA_SEND_DESTRUCTION))
{
outBitstream.Reset();
outBitstream.Write((unsigned char)ID_REPLICA_MANAGER_DESTRUCTION);
outBitstream.Write(replica->GetNetworkID());
replica->SendDestruction(&outBitstream, participantStruct->playerId);
if (outBitstream.GetNumberOfBitsUsed()>0)
{
rakPeer->Send(&outBitstream, HIGH_PRIORITY, RELIABLE_ORDERED, sendChannel, participantStruct->playerId, false);
}
}
// Remove any pending commands that reference this object, for this player
tempIndex = participantStruct->commandList.GetIndexFromKey(replica, &objectExists);
if (objectExists)
participantStruct->commandList.RemoveAtIndex(tempIndex);
// Remove any remote object state tracking for this object, for this player
tempIndex = participantStruct->remoteObjectList.GetIndexFromKey(replica, &objectExists);
if (objectExists)
participantStruct->remoteObjectList.RemoveAtIndex(tempIndex);
}
else if (replicaReferenced==false)
{
// See if any commands or objects reference replica
if (participantStruct->commandList.HasData(replica))
replicaReferenced=true;
else if (participantStruct->remoteObjectList.HasData(replica))
replicaReferenced=true;
}
}
// Remove replica from the list if no commands and no remote objects reference it
if (replicaReferenced==false)
replicatedObjects.RemoveAtIndex(replicatedObjectsIndex);
}
示例2: SendPlayerPoolToPlayer
void SendPlayerPoolToPlayer(PLAYERID playerID)
{
// let the player know about all the players in the server
for(PLAYERID p = 0; p < MAX_PLAYERS; p++)
{
if(!playerPool[p].iIsConnected)
continue;
if(p == playerID)
continue;
BYTE byteNameLen = (BYTE)strlen(playerPool[p].szPlayerName);
RakNet::BitStream bs;
bs.Reset();
bs.Write(p);
bs.Write((int)1);
bs.Write((BYTE)0);
bs.Write(byteNameLen);
bs.Write(playerPool[p].szPlayerName, byteNameLen);
pRakServer->RPC(&RPC_ServerJoin, &bs, HIGH_PRIORITY, RELIABLE,
0, pRakServer->GetPlayerIDFromIndex(playerID), FALSE, FALSE, UNASSIGNED_NETWORK_ID, NULL);
Sleep(5); // well, shit.
}
}
示例3: PushReference
void FileListTransfer::PushReference(SystemAddress systemAddress)
{
// Was previously using GetStatistics to get outgoing buffer size, but TCP with UnifiedSend doesn't have this
unsigned int i=0;
unsigned int bytesRead;
char *dataBlocks[2];
int lengths[2];
RakNet::BitStream outBitstream;
while (i < filesToPush.Size())
{
if (filesToPush[i].systemAddress==systemAddress)
{
outBitstream.Reset();
outBitstream.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH);
outBitstream.Write(filesToPush[i].fileListNode.context);
outBitstream.Write(filesToPush[i].setID);
stringCompressor->EncodeString(filesToPush[i].fileListNode.filename, 512, &outBitstream);
outBitstream.WriteCompressed(filesToPush[i].setIndex);
outBitstream.WriteCompressed(filesToPush[i].fileListNode.dataLengthBytes); // Original length in bytes
// Read and send chunk. If done, delete at this index
void *buff = rakMalloc_Ex(filesToPush[i].chunkSize, __FILE__, __LINE__);
if (buff==0)
{
notifyOutOfMemory(__FILE__, __LINE__);
continue;
}
bytesRead=filesToPush[i].incrementalReadInterface->GetFilePart(filesToPush[i].fileListNode.fullPathToFile, filesToPush[i].currentOffset, filesToPush[i].chunkSize, buff, filesToPush[i].fileListNode.context);
outBitstream.WriteCompressed(filesToPush[i].currentOffset);
filesToPush[i].currentOffset+=bytesRead;
outBitstream.WriteCompressed(bytesRead);
bool done = bytesRead!=filesToPush[i].chunkSize;
outBitstream.Write(done);
if (callback)
{
callback->OnFilePush(filesToPush[i].fileListNode.filename, filesToPush[i].fileListNode.fileLengthBytes, filesToPush[i].currentOffset-bytesRead, bytesRead, done, filesToPush[i].systemAddress);
}
dataBlocks[0]=(char*) outBitstream.GetData();
lengths[0]=outBitstream.GetNumberOfBytesUsed();
dataBlocks[1]=(char*) buff;
lengths[1]=bytesRead;
//rakPeerInterface->SendList(dataBlocks,lengths,2,filesToPush[i].packetPriority, RELIABLE_ORDERED, filesToPush[i].orderingChannel, filesToPush[i].systemAddress, false);
SendListUnified(dataBlocks,lengths,2,filesToPush[i].packetPriority, RELIABLE_ORDERED, filesToPush[i].orderingChannel, filesToPush[i].systemAddress, false);
if (done)
{
// Done
RakNet::OP_DELETE_ARRAY(filesToPush[i].fileListNode.filename, __FILE__, __LINE__);
filesToPush.RemoveAtIndex(i);
}
rakFree_Ex(buff, __FILE__, __LINE__ );
return;
}
else
i++;
}
}
示例4: OnClosedConnection
void NatPunchthroughServer::OnClosedConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
{
(void) lostConnectionReason;
(void) systemAddress;
unsigned int i=0;
bool objectExists;
i = users.GetIndexFromKey(rakNetGUID, &objectExists);
if (objectExists)
{
RakNet::BitStream outgoingBs;
DataStructures::List<User *> freedUpInProgressUsers;
User *user = users[i];
User *otherUser;
unsigned int connectionAttemptIndex;
ConnectionAttempt *connectionAttempt;
for (connectionAttemptIndex=0; connectionAttemptIndex < user->connectionAttempts.Size(); connectionAttemptIndex++)
{
connectionAttempt=user->connectionAttempts[connectionAttemptIndex];
outgoingBs.Reset();
if (connectionAttempt->recipient==user)
{
otherUser=connectionAttempt->sender;
}
else
{
otherUser=connectionAttempt->recipient;
}
// 05/28/09 Previously only told sender about ID_NAT_CONNECTION_TO_TARGET_LOST
// However, recipient may be expecting it due to external code
// In that case, recipient would never get any response if the sender dropped
outgoingBs.Write((MessageID)ID_NAT_CONNECTION_TO_TARGET_LOST);
outgoingBs.Write(rakNetGUID);
outgoingBs.Write(connectionAttempt->sessionId);
rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,otherUser->systemAddress,false);
// 4/22/09 - Bug: was checking inProgress, legacy variable not used elsewhere
if (connectionAttempt->attemptPhase==ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS)
{
otherUser->isReady=true;
freedUpInProgressUsers.Insert(otherUser, _FILE_AND_LINE_ );
}
otherUser->DeleteConnectionAttempt(connectionAttempt);
}
RakNet::OP_DELETE(users[i], _FILE_AND_LINE_);
users.RemoveAtIndex(i);
for (i=0; i < freedUpInProgressUsers.Size(); i++)
{
StartPunchthroughForUser(freedUpInProgressUsers[i]);
}
}
}
示例5: Packet_NewIncomingConnection
void CRcon::Packet_NewIncomingConnection(Packet* pPacket)
{
in_addr in;
in.s_addr = pPacket->playerId.binaryAddress;
logprintf("[RCON] Admin [%s] has connected.", inet_ntoa(in));
RakNet::BitStream bsSend;
char* szHostname = pConsole->GetStringVariable( "hostname" );
BYTE byteHostnameLength = strlen(szHostname);
CPlayerPool* pPlayerPool = pNetGame->GetPlayerPool();
bsSend.Write( byteHostnameLength );
bsSend.Write( szHostname, byteHostnameLength );
m_pRakServer->RPC( RPC_RconConnect,&bsSend,HIGH_PRIORITY,RELIABLE,0,UNASSIGNED_PLAYER_ID,true,false);
bsSend.Reset();
for( int i = 0; i < MAX_PLAYERS; i++ )
{
if( pPlayerPool->GetSlotState(i) == TRUE )
{
bsSend.Write((BYTE)i);
bsSend.Write(pPlayerPool->GetPlayerName(i),MAX_PLAYER_NAME);
pRcon->GetRakServer()->RPC( RPC_ServerJoin, &bsSend, HIGH_PRIORITY, RELIABLE, 0,
UNASSIGNED_PLAYER_ID, true, false );
bsSend.Reset();
PLAYER_DATA playerData = GetPlayerInformation( i );
bsSend.Write( (BYTE)i );
bsSend.Write( (PCHAR)&playerData, sizeof(PLAYER_DATA) );
pRcon->GetRakServer()->RPC( RPC_RconPlayerInfo, &bsSend, HIGH_PRIORITY, RELIABLE, 0,
UNASSIGNED_PLAYER_ID, true, false );
bsSend.Reset();
}
}
}
示例6:
void ConnectionGraph2::AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID)
{
// Relay the new connection to other systems.
RakNet::BitStream bs;
bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
bs.Write((uint32_t)1);
bs.Write(systemAddress);
bs.Write(rakNetGUID);
bs.WriteCasted<uint16_t>(rakPeerInterface->GetAveragePing(rakNetGUID));
SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true);
// Send everyone to the new guy
DataStructures::List<SystemAddress> addresses;
DataStructures::List<RakNetGUID> guids;
rakPeerInterface->GetSystemList(addresses, guids);
bs.Reset();
bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
BitSize_t writeOffset = bs.GetWriteOffset();
bs.Write((uint32_t) addresses.Size());
unsigned int i;
uint32_t count=0;
for (i=0; i < addresses.Size(); i++)
{
if (addresses[i]==systemAddress)
continue;
bs.Write(addresses[i]);
bs.Write(guids[i]);
bs.WriteCasted<uint16_t>(rakPeerInterface->GetAveragePing(guids[i]));
count++;
}
if (count>0)
{
BitSize_t writeOffset2 = bs.GetWriteOffset();
bs.SetWriteOffset(writeOffset);
bs.Write(count);
bs.SetWriteOffset(writeOffset2);
SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,false);
}
bool objectExists;
unsigned int ii = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists);
if (objectExists==false)
{
RemoteSystem* remoteSystem = RakNet::OP_NEW<RemoteSystem>(_FILE_AND_LINE_);
remoteSystem->guid=rakNetGUID;
remoteSystems.InsertAtIndex(remoteSystem,ii,_FILE_AND_LINE_);
}
}
示例7: CreateMissile
void Application::CreateMissile(float x, float y, float w, int id)
{
#ifdef NETWORKMISSLE
// Lab 13 Task 9b : Implement networked version of createmissile
RakNet::BitStream bs;
unsigned char msgid;
unsigned char deleted = 0;
if (mymissile)
{
//sendupdatethroughnetworktodeletethismissile
deleted = 1;
msgid = ID_UPDATEMISSILE;
bs.Write(msgid);
bs.Write(id);
bs.Write(deleted);
bs.Write(x);
bs.Write(y);
bs.Write(w);
rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0,
UNASSIGNED_SYSTEM_ADDRESS, true);
//deleteexistingmissile
delete mymissile;
mymissile = 0;
}
//addanewmissilebasedonthefollowingparametercoordinates
mymissile = new Missile("missile.png", x, y, w, id);
//sendnetworkcommandtoaddnewmissile
bs.Reset();
msgid = ID_NEWMISSILE;
bs.Write(msgid);
bs.Write(id);
bs.Write(x);
bs.Write(y);
bs.Write(w);
rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0,
UNASSIGNED_SYSTEM_ADDRESS, true);
#else
// Lab 13 Task 3 : Implement local version missile creation
if (mymissile) // Delete existing missle
{
delete mymissile;
mymissile = NULL;
}
// Add missle
mymissile = new Missile("missile.png", x, y, w, id);
#endif
}
示例8: SendWelcomePackage
void ServerApp::SendWelcomePackage(SystemAddress& addr)
{
++newID;
unsigned int shipcount = static_cast<unsigned int>(clients_.size());
unsigned char msgid = ID_WELCOME;
RakNet::BitStream bs;
bs.Write(msgid);
bs.Write(newID);
bs.Write(shipcount);
// Send all existing ships
for (ClientMap::iterator itr = clients_.begin(); itr != clients_.end(); ++itr)
{
std::cout << "Ship " << itr->second.id << " pos" << itr->second.x_ << " " << itr->second.y_ << std::endl;
bs.Write( itr->second.id );
bs.Write( itr->second.x_ );
bs.Write( itr->second.y_ );
bs.Write( itr->second.type_ );
}
for (vector<ServerEnemy*>::iterator it = enemyList.begin(); it != enemyList.end(); ++it)
{
ServerEnemy* e = *it;
bs.Write(e->id);
bs.Write(e->active);
bs.Write(e->type_);
bs.Write(e->x_);
bs.Write(e->y_);
bs.Write(e->vel_x);
bs.Write(e->vel_y);
bs.Write(e->speed);
bs.Write(e->hp);
}
bs.Write(base_hp);
rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED,0, addr, false);
bs.Reset();
ServerGameObject newobject(newID);
newobject.active = true;
clients_.insert(std::make_pair(addr, newobject));
clientList.push_back(addr); // Add client to list
std::cout << "New guy, assigned id " << newID << std::endl;
}
示例9:
void ConnectionGraph2::OnNewConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID, bool isIncoming)
{
(void) isIncoming;
// Send all existing systems to new connection
RakNet::BitStream bs;
bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
bs.Write((unsigned int)1);
bs.Write(systemAddress);
bs.Write(rakNetGUID);
SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true);
// Send everyone to the new guy
DataStructures::List<SystemAddress> addresses;
DataStructures::List<RakNetGUID> guids;
rakPeerInterface->GetSystemList(addresses, guids);
bs.Reset();
bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION);
BitSize_t writeOffset = bs.GetWriteOffset();
bs.Write((unsigned int) addresses.Size());
unsigned int i;
unsigned int count=0;
for (i=0; i < addresses.Size(); i++)
{
if (addresses[i]==systemAddress)
continue;
bs.Write(addresses[i]);
bs.Write(guids[i]);
count++;
}
if (count>0)
{
BitSize_t writeOffset2 = bs.GetWriteOffset();
bs.SetWriteOffset(writeOffset);
bs.Write(count);
bs.SetWriteOffset(writeOffset2);
SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,false);
}
RemoteSystem* remoteSystem = RakNet::OP_NEW<RemoteSystem>(__FILE__,__LINE__);
remoteSystem->guid=rakNetGUID;
remoteSystems.Insert(rakNetGUID,remoteSystem,true,__FILE__,__LINE__);
}
示例10: update
bool CNetwork::update()
{
Packet *packet = m_peer->Receive();
while(packet)
{
handlePacket(packet);
m_peer->DeallocatePacket(packet);
packet = m_peer->Receive();
}
if (m_readTimer->elapsed() > m_tick_rate)
{
RakNet::BitStream bs;
typedef std::map<int, CompLocation*> LocationMap;
BOOST_FOREACH(LocationMap::value_type value, CKernel::data()->getAllLocation())
{
//TODO(#2#) BE SURE ABOUT NETWORK PERFORMANCE
if(value.second->getTick() == m_tick)
{
bs.Reset();
bs.Write((MessageID)ID_ENTITY_POS);
bs.Write(value.first);
bs.Write(value.second->position());
bs.Write(value.second->direction());
bs.Write(value.second->velocity());
CompInfo* info = CKernel::data()->getGameObjectInfo(value.first);
if (info)
{
sendToAllInMap(info->map(), bs);
}
}
}
m_readTimer->restart();
if(m_tick >= m_tick_max) m_tick = 0;
else ++m_tick;
}
示例11: SendOOBFromSpecifiedSocket
void Router2::SendOOBMessages(Router2::MiniPunchRequest *mpr)
{
// Mini NAT punch
// Send from srcToDestPort to packet->systemAddress (source). If the message arrives, the remote system should reply.
SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->sourceAddress, mpr->forwardingSocket);
// Send from destToSourcePort to endpointSystemAddress (destination). If the message arrives, the remote system should reply.
SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->endpointAddress, mpr->forwardingSocket);
if (debugInterface) {
char buff [512];
char buff2[128];
mpr->sourceAddress .ToString(true,buff2);
debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2));
mpr->endpointAddress .ToString(true,buff2);
debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2));
}
// Tell source to send to forwardingPort
RakNet::BitStream extraData;
extraData.Write(mpr->forwardingPort);
RakAssert(mpr->forwardingPort!=0);
SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->sourceAddress);
// Tell destination to send to forwardingPort
extraData.Reset();
extraData.Write(mpr->forwardingPort);
RakAssert(mpr->forwardingPort);
SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->endpointAddress);
}
示例12: RunTest
//.........这里部分代码省略.........
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 (RakNet::GetTime()-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;
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>=97)//This is our last 3 loops, give it time to send packet and arrive on interface, 2 seconds is more than enough
{
RakSleep(2000);
}
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);
示例13: main
int main(int argc, char **argv)
{
RakPeerInterface *rakPeer;
char str[256];
char ip[32];
unsigned short remotePort, localPort;
RakNet::Packet *packet;
printf("This project tests sending a burst of messages to a remote system.\n");
printf("Difficulty: Beginner\n\n");
rakPeer = RakNet::RakPeerInterface::GetInstance();
printf("Enter remote IP (enter to not connect): ");
Gets(ip, sizeof(ip));
if (ip[0])
{
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);
RakNet::SocketDescriptor socketDescriptor(localPort,0);
rakPeer->Startup(32, &socketDescriptor, 1);
printf("Connecting...\n");
rakPeer->Connect(ip, remotePort, 0, 0);
}
else
{
printf("Enter local port: ");
Gets(str, sizeof(str));
if (str[0]==0)
strcpy(str, "60000");
localPort=atoi(str);
RakNet::SocketDescriptor socketDescriptor(localPort,0);
rakPeer->Startup(32, &socketDescriptor, 1);
}
rakPeer->SetMaximumIncomingConnections(32);
printf("'s' to send. ' ' for statistics. 'q' to quit.\n");
while (1)
{
if (kbhit())
{
char ch=getch();
if (ch=='q')
return 1;
else if (ch==' ')
{
RakNetStatistics *rss;
char message[2048];
rss=rakPeer->GetStatistics(rakPeer->GetSystemAddressFromIndex(0));
StatisticsToString(rss, message, 2);
printf("%s", message);
}
else if (ch=='s')
{
char msgSizeStr[128], msgCountStr[128];
uint32_t msgSize, msgCount,index;
printf("Enter message size in bytes: ");
Gets(msgSizeStr, sizeof(msgSizeStr));
if (msgSizeStr[0]==0)
msgSize=4096;
else
msgSize=atoi(msgSizeStr);
printf("Enter times to repeatedly send message: ");
Gets(msgCountStr, sizeof(msgCountStr));
if (msgCountStr[0]==0)
msgCount=128;
else
msgCount=atoi(msgCountStr);
RakNet::BitStream bitStream;
for (index=0; index < msgCount; index++)
{
bitStream.Reset();
bitStream.Write((MessageID)ID_USER_PACKET_ENUM);
bitStream.Write(msgSize);
bitStream.Write(index);
bitStream.Write(msgCount);
bitStream.PadWithZeroToByteLength(msgSize);
rakPeer->Send(&bitStream, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
}
printf("Sent\n");
}
}
for (packet=rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet=rakPeer->Receive())
{
switch(packet->data[0])
//.........这里部分代码省略.........
示例14: Update
void NatTypeDetectionServer::Update(void)
{
int i=0;
RakNet::TimeMS time = RakNet::GetTimeMS();
RakNet::BitStream bs;
SystemAddress boundAddress;
// Only socket that receives messages is s3p4, to see if the external address is different than that of the connection to rakPeerInterface
char data[ MAXIMUM_MTU_SIZE ];
int len;
SystemAddress senderAddr;
len=NatTypeRecvFrom(data, s3p4, senderAddr);
// Client is asking us if this is port restricted. Only client requests of this type come in on s3p4
while (len>0 && data[0]==NAT_TYPE_PORT_RESTRICTED)
{
RakNet::BitStream bsIn((unsigned char*) data,len,false);
RakNetGUID senderGuid;
bsIn.IgnoreBytes(sizeof(MessageID));
bool readSuccess = bsIn.Read(senderGuid);
RakAssert(readSuccess);
if (readSuccess)
{
unsigned int i = GetDetectionAttemptIndex(senderGuid);
if (i!=(unsigned int)-1)
{
bs.Reset();
bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT);
// If different, then symmetric
if (senderAddr!=natDetectionAttempts[i].systemAddress)
{
printf("Determined client is symmetric\n");
bs.Write((unsigned char) NAT_TYPE_SYMMETRIC);
}
else
{
// else port restricted
printf("Determined client is port restricted\n");
bs.Write((unsigned char) NAT_TYPE_PORT_RESTRICTED);
}
rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,natDetectionAttempts[i].systemAddress,false);
// Done
natDetectionAttempts.RemoveAtIndexFast(i);
}
else
{
// RakAssert("i==0 in Update when looking up GUID in NatTypeDetectionServer.cpp. Either a bug or a late resend" && 0);
}
}
else
{
// RakAssert("Didn't read GUID in Update in NatTypeDetectionServer.cpp. Message format error" && 0);
}
len=NatTypeRecvFrom(data, s3p4, senderAddr);
}
while (i < (int) natDetectionAttempts.Size())
{
if (time > natDetectionAttempts[i].nextStateTime)
{
natDetectionAttempts[i].detectionState=(NATDetectionState)((int)natDetectionAttempts[i].detectionState+1);
natDetectionAttempts[i].nextStateTime=time+natDetectionAttempts[i].timeBetweenAttempts;
SystemAddress saOut;
unsigned char c;
bs.Reset();
switch (natDetectionAttempts[i].detectionState)
{
case STATE_TESTING_NONE_1:
case STATE_TESTING_NONE_2:
c = NAT_TYPE_NONE;
printf("Testing NAT_TYPE_NONE\n");
// S4P5 sends to C2. If arrived, no NAT. Done. (Else S4P5 potentially banned, do not use again).
saOut=natDetectionAttempts[i].systemAddress;
saOut.SetPort(natDetectionAttempts[i].c2Port);
SocketLayer::SendTo_PC( s4p5, (const char*) &c, 1, saOut, __FILE__, __LINE__ );
break;
case STATE_TESTING_FULL_CONE_1:
case STATE_TESTING_FULL_CONE_2:
printf("Testing NAT_TYPE_FULL_CONE\n");
rakPeerInterface->WriteOutOfBandHeader(&bs);
bs.Write((unsigned char) ID_NAT_TYPE_DETECT);
bs.Write((unsigned char) NAT_TYPE_FULL_CONE);
// S2P3 sends to C1 (Different address, different port, to previously used port on client). If received, Full-cone nat. Done. (Else S2P3 potentially banned, do not use again).
saOut=natDetectionAttempts[i].systemAddress;
saOut.SetPort(natDetectionAttempts[i].systemAddress.GetPort());
SocketLayer::SendTo_PC( s2p3, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ );
break;
case STATE_TESTING_ADDRESS_RESTRICTED_1:
case STATE_TESTING_ADDRESS_RESTRICTED_2:
printf("Testing NAT_TYPE_ADDRESS_RESTRICTED\n");
rakPeerInterface->WriteOutOfBandHeader(&bs);
bs.Write((unsigned char) ID_NAT_TYPE_DETECT);
bs.Write((unsigned char) NAT_TYPE_ADDRESS_RESTRICTED);
// S1P2 sends to C1 (Same address, different port, to previously used port on client). If received, address-restricted cone nat. Done.
saOut=natDetectionAttempts[i].systemAddress;
saOut.SetPort(natDetectionAttempts[i].systemAddress.GetPort());
SocketLayer::SendTo_PC( s1p2, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ );
//.........这里部分代码省略.........
示例15: RunTest
//.........这里部分代码省略.........
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: