コード例 #1
0
void packAndSendGameState(RakNet::RakPeerInterface& _krPeer, map<RakNet::NetworkID, Entity*>& _players,
		const Circle* _kpFoodModel)
{
	RakNet::BitStream stream;
	stream.Write((RakNet::MessageID) MessageIdentifiers::ID_SNAKE_STATES);
	stream.Write(_players.size());

	for (map<RakNet::NetworkID, Entity*>::iterator playerIter = _players.begin();
		playerIter != _players.end(); playerIter++)
	{
		Entity* pSnake = playerIter->second;
		stream.Write(playerIter->first);
		stream.Write(pSnake->getSingleComponent<Componentizer<unsigned int> >()->getValue());

		vector<Vector2> segmentPositions = pSnake->getSingleComponent<CSnakeModel>()->getSegmentPositions();
		stream.Write(segmentPositions.size());

		for (unsigned int uiSegmentIndex = 0; uiSegmentIndex < segmentPositions.size(); uiSegmentIndex++)
		{
			stream.Write(segmentPositions[uiSegmentIndex]);
		}
	}

	if (_kpFoodModel == NULL)
	{
		stream.Write(false);
	}
	else
	{
		stream.Write(true);
		stream.Write(_kpFoodModel->getPosition());
	}

	_krPeer.Send(&stream, IMMEDIATE_PRIORITY, UNRELIABLE, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
コード例 #2
0
    void Listen()
    {
        RakNet::Packet* packet;
        while(running)
        {
            for(packet = peer->Receive(); packet; peer->DeallocatePacket(packet), packet = peer->Receive())
            {
                if(packet->data[0] == ID_SERVER_RELAY_MESSAGE)
                {
                    // recieved a message; print to screen
                    RakNet::RakString rs;
                    RakNet::BitStream bsIn(packet->data, packet->length, false);
                    bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
                    bsIn.Read(rs);
                    printf("[MSG] ");
                    printf(rs);
                    printf("\n");
                }
                else if(packet->data[0] == ID_CLIENT_CHAT_MESSAGE)
                {
                    // client sent a message, server needs to broadcast it to everyone.
                    RakNet::RakString rs;
                    RakNet::BitStream bsIn(packet->data, packet->length, false);
                    bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
                    bsIn.Read(rs);
                    printf("[MSG] ");
                    printf(rs);
                    printf("\n");

                    RakNet::BitStream bsOut;
                    bsOut.Write((RakNet::MessageID)ID_SERVER_RELAY_MESSAGE);
                    bsOut.Write(rs);

                    peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, true);
                }
                else if(packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED)
                {
                    printf("[SYS] connected to server.\n");
                    connections.push_back(RakNet::AddressOrGUID(packet));
                }
                else if(packet->data[0] == ID_NEW_INCOMING_CONNECTION)
                {
                    printf("[SYS] client joined server.\n");
                    connections.push_back(RakNet::AddressOrGUID(packet));
                }
            }
        }
    }
コード例 #3
0
    void Broadcast()
    {
        while(running)
        {
            char message[512];
            gets(message);

            if(message[0] == '~')
            {
                running = false;
                return;
            }

            RakNet::BitStream bsOut;
            bsOut.Write((RakNet::MessageID)ID_CLIENT_CHAT_MESSAGE);
            bsOut.Write(message);

            for(int i = 0; i < connections.size(); i++)
            {
                peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, connections[i], false);
            }
        }
    }
コード例 #4
0
ファイル: main.cpp プロジェクト: GreatDivine/GameNetworking
int main()
{
	char str[512];
	RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
	bool isServer;
	RakNet::Packet *packet;

	printf("(C)lient or (S)erver?\n");
	gets(str);

	if ((str[0] == 'c') || (str[0] == 'C'))
	{
		RakNet::SocketDescriptor sd;
		peer->Startup(1, &sd, 1);
		isServer = false;
	}

	else
	{
		RakNet::SocketDescriptor sd(SERVER_PORT, 0);
		peer->Startup(MAX_CLIENTS, &sd, 1);
		isServer = true;
	}

	if (isServer)
	{
		printf("Starting the server.\n");
		peer->SetMaximumIncomingConnections(MAX_CLIENTS);
	}
	else
	{
		printf("Enter server IP or hit enter for default: 127.0.0.1\n");
		gets(str);
		if (str[0] == 0)
		{
			strcpy(str, "127.0.0.1");
		}

		printf("Starting the client.\n");
		peer->Connect(str, SERVER_PORT, 0, 0);
	}

	while (1)
	{
		for (packet = peer->Receive(); packet; peer->DeallocatePacket(packet), packet = peer->Receive())
		{
			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				printf("Another client has dosconnected\n");
				break;

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

			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				printf("Another client has connected\n");
				break;

			case ID_CONNECTION_REQUEST_ACCEPTED:
				printf("Our connection request has been accepted.\n");
				{
					RakNet::BitStream bsOut;
					bsOut.Write((RakNet::MessageID)ID_GAME_MESSAGE_1);
					bsOut.Write("Hello World");
					peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false);
				}
				break;

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

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

			case ID_DISCONNECTION_NOTIFICATION:
				{
					if (isServer)
					{
						printf("A client has disconnected.\n");
					}
					else
					{
						printf("We have been disconnected.\n");
					}
				}
				break;

			case ID_GAME_MESSAGE_1:
				{
					RakNet::RakString rs;
					RakNet::BitStream bsIn(packet->data, packet->length, false);
					bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
					bsIn.Read(rs);
					printf("%s\n", rs.C_String());
				}
				break;

			default:
				printf("Message with identifier %i has arrived.\n", packet->data[0]);
				break;
			}
		}
	}

	RakNet::RakPeerInterface::DestroyInstance(peer);

	return 0;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: Darrenbydesign/HoloToolkit
int main()
{
	RakNet::Packet *packet;
	RakNet::RakPeerInterface *rakPeer;
	bool isConnected=false;
	rakPeer=RakNet::RakPeerInterface::GetInstance();
	char command[512];
	printf("This sample demonstrates connecting to the command console.\n");
	printf("using the RakNet transport protocol\n");
	printf("It's the equivalent of a secure telnet client\n");
	printf("See the 'CommandConsoleServer' project.\n");
	printf("Difficulty: Intermediate\n\n");

	printf("RakNet secure command console.\n");
	printf("Commands:\n");
	printf("/Connect\n");
	printf("/Disconnect\n");
	printf("/Quit\n");
	printf("Any other command goes to the remote console\n");
	while (1)
	{
		if (kbhit())
		{
			Gets(command,sizeof(command));

			if (stricmp(command, "/quit")==0)
			{
				printf("Goodbye.\n");
				rakPeer->Shutdown(500, 0);
				return 0;
			}
			else if (stricmp(command, "/disconnect")==0)
			{
				if (isConnected)
				{
					rakPeer->Shutdown(500, 0);
					isConnected=false;
					printf("Disconnecting.\n");
				}
				else
				{
					printf("Not currently connected.\n");
				}
			}
			else if (stricmp(command, "/connect")==0)
			{
				if (isConnected)
				{
					printf("Disconnect first.\n");
				}
				else
				{
					char ip[128];
					char remotePort[64];
					char password[512];
					char localPort[64];
					printf("Enter remote IP: ");
					do {
						Gets(ip, sizeof(ip));
					} while(ip[0]==0);
					printf("Enter remote port: ");
					do {
						Gets(remotePort,sizeof(remotePort));
					} while(remotePort[0]==0);
					printf("Enter local port (enter for 0): ");
					Gets(localPort,sizeof(localPort));
					if (localPort[0]==0)
					{
						strcpy(localPort, "0");
					}
					printf("Enter console password (enter for none): ");
					Gets(password,sizeof(password));
					RakNet::SocketDescriptor socketDescriptor((int) atoi(localPort),0);
					if (rakPeer->Startup(1, &socketDescriptor, 1)==RakNet::RAKNET_STARTED)
					{
						int passwordLen;
						if (password[0])
							passwordLen=(int) strlen(password)+1;
						else
							passwordLen=0;
						if (rakPeer->Connect(ip, (int) atoi(remotePort), password, passwordLen)==RakNet::CONNECTION_ATTEMPT_STARTED)
							printf("Connecting...\nNote: if the password is wrong the other system will ignore us.\n");
						else
						{
							printf("Connect call failed.\n");
							rakPeer->Shutdown(0, 0);
						}
					}
					else
						printf("Initialize call failed.\n");					
					
				}				
			}
			else
			{
				if (isConnected)
				{
					RakNet::BitStream str;
					str.Write((unsigned char) ID_TRANSPORT_STRING);
					str.Write(command, (int) strlen(command)+1);
					rakPeer->Send(&str, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
				}
				else
				{
					printf("You must be connected to send commands.\n");
				}
			}
		}

		packet = rakPeer->Receive();
		if (packet)
		{
			switch (packet->data[0])
			{
			case ID_DISCONNECTION_NOTIFICATION:
				printf("The server disconnected us.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_BANNED:
				printf("We are banned from this server.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				printf("Connection attempt failed.\nThe password was wrong or there is no responsive machine at that IP/port.\n");
				isConnected=false;
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				printf("Server is full.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_LOST:
				printf("We lost the connection.\n");
				isConnected=false;
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				printf("Connection accepted.\n");
				isConnected=true;
				break;
			case ID_TRANSPORT_STRING:
				printf("%s", packet->data+1);
				break;
			}

			rakPeer->DeallocatePacket(packet);
		}

		// This sleep keeps RakNet responsive
#ifdef _WIN32
		Sleep(30);
#else
		usleep(30 * 1000);
#endif
	}

	return 0;
}
コード例 #6
0
ファイル: Utils.cpp プロジェクト: GrimKriegor/openmw-tes3mp
ServerExtendedData getExtendedData(const char *addr, unsigned short port)
{
    ServerExtendedData data;
    RakNet::SocketDescriptor socketDescriptor = {0, ""};
    RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
    peer->Startup(1, &socketDescriptor, 1);

    stringstream sstr;
    sstr << TES3MP_VERSION;
    sstr << TES3MP_PROTO_VERSION;

    std::string msg;

    if (peer->Connect(addr, port, sstr.str().c_str(), (int)(sstr.str().size()), nullptr, 0, 3, 500, 0) != RakNet::CONNECTION_ATTEMPT_STARTED)
        msg = "Connection attempt failed.\n";


    int queue = 0;
    while (queue == 0)
    {
        for (RakNet::Packet *packet = peer->Receive(); packet; peer->DeallocatePacket(
                packet), packet = peer->Receive())
        {
            switch (packet->data[0])
            {
                case ID_CONNECTION_ATTEMPT_FAILED:
                {
                    msg = "Connection failed.\n"
                            "Either the IP address is wrong or a firewall on either system is blocking\n"
                            "UDP packets on the port you have chosen.";
                    queue = -1;
                    break;
                }
                case ID_INVALID_PASSWORD:
                {
                    msg = "Connection failed.\n"
                            "The client or server is outdated.\n";
                    queue = -1;
                    break;
                }
                case ID_CONNECTION_REQUEST_ACCEPTED:
                {
                    msg = "Connection accepted.\n";
                    queue = 1;
                    break;
                }
                case ID_DISCONNECTION_NOTIFICATION:
                    throw runtime_error("ID_DISCONNECTION_NOTIFICATION.\n");
                case ID_CONNECTION_BANNED:
                    throw runtime_error("ID_CONNECTION_BANNED.\n");
                case ID_CONNECTION_LOST:
                    throw runtime_error("ID_CONNECTION_LOST.\n");
                default:
                    printf("Connection message with identifier %i has arrived in initialization.\n", packet->data[0]);
            }
        }
    }
    puts(msg.c_str());

    if (queue == -1) // connection is failed
        return data;

    {
        RakNet::BitStream bs;
        bs.Write((unsigned char) (ID_USER_PACKET_ENUM + 1));
        peer->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
    }

    RakNet::Packet *packet;
    bool done = false;
    while (!done)
    {
        for (packet = peer->Receive(); packet; peer->DeallocatePacket(packet), packet = peer->Receive())
        {
            if (packet->data[0] == (ID_USER_PACKET_ENUM + 1))
            {
                RakNet::BitStream bs(packet->data, packet->length, false);
                bs.IgnoreBytes(1);
                size_t length = 0;
                bs.Read(length);
                for (size_t i = 0; i < length; i++)
                {
                    RakNet::RakString str;
                    bs.Read(str);
                    data.players.emplace_back(str.C_String());
                }
                bs.Read(length);
                for (size_t i = 0; i < length; i++)
                {
                    RakNet::RakString str;
                    bs.Read(str);
                    data.plugins.emplace_back(str.C_String());
                }
                done = true;
            }
        }
    }

    peer->Shutdown(0);
    RakSleep(10);
    RakNet::RakPeerInterface::DestroyInstance(peer);
    return data;
}
コード例 #7
0
int main(int argc, char** argv) {
	RakNet::RakPeerInterface *server = RakNet::RakPeerInterface::GetInstance();
	RakNet::Packet* p;
	unsigned char packetIdentifier;
	RakNet::SystemAddress clientID = RakNet::UNASSIGNED_SYSTEM_ADDRESS;
	RakNet::RakNetStatistics *rss;
	RakNet::SocketDescriptor socketDescriptors[2];
	char portstring[30];

	socketDescriptors[0].port = SERVER_PORT;
	socketDescriptors[0].socketFamily = AF_INET; // Test out IPV4
	socketDescriptors[1].port = SERVER_PORT;
	socketDescriptors[1].socketFamily = AF_INET6; // Test out IPV6
	if (server->Startup(4, socketDescriptors, 2) != RakNet::RAKNET_STARTED) {
		std::cout << "IPV6 not supported, starting with IPV4-only interface..." << std::endl;
		if (server->Startup(4, socketDescriptors, 1) != RakNet::RAKNET_STARTED) {
			std::cerr << "Error creating server, exiting..." << std::endl;
			exit(-1);
		}
	}
	std::cout << "Server started successfully. Listening on port " << SERVER_PORT << std::endl;
	server->SetMaximumIncomingConnections(20);
	server->SetOccasionalPing(true);
	server->SetUnreliableTimeout(1000);

	DataStructures::List<RakNet::RakNetSocket2*> sockets;
	server->GetSockets(sockets);
	std::cout << "Socket addresses used by RakNet:" << std::endl;
	for (unsigned int i = 0; i < sockets.Size(); i++) {
		printf("%i. %s\n", i + 1, sockets[i]->GetBoundAddress().ToString(true));
	}
	char message[2048];

	// Loop for input
	while (1)
	{

		// This sleep keeps RakNet responsive
		RakSleep(30);

		if (kbhit())
		{
			// Notice what is not here: something to keep our network running.  It's
			// fine to block on gets or anything we want
			// Because the network engine was painstakingly written using threads.
			Gets(message, sizeof(message));

			if (strcmp(message, "quit") == 0)
			{
				puts("Quitting.");
				break;
			}

			if (strcmp(message, "stat") == 0)
			{
				rss = server->GetStatistics(server->GetSystemAddressFromIndex(0));
				StatisticsToString(rss, message, 2);
				printf("%s", message);
				printf("Ping %i\n", server->GetAveragePing(server->GetSystemAddressFromIndex(0)));

				continue;
			}

			if (strcmp(message, "ping") == 0)
			{
				server->Ping(clientID);

				continue;
			}

			if (strcmp(message, "pingip") == 0)
			{
				printf("Enter IP: ");
				Gets(message, sizeof(message));
				printf("Enter port: ");
				Gets(portstring, sizeof(portstring));
				if (portstring[0] == 0)
					strcpy(portstring, "1234");
				server->Ping(message, atoi(portstring), false);

				continue;
			}

			if (strcmp(message, "kick") == 0)
			{
				server->CloseConnection(clientID, true, 0);

				continue;
			}

			if (strcmp(message, "getconnectionlist") == 0)
			{
				printf("Connections:\n");
				RakNet::SystemAddress systems[10];
				unsigned short numConnections = 10;
				server->GetConnectionList((RakNet::SystemAddress*) &systems, &numConnections);
				for (int i = 0; i < numConnections; i++)
				{
					printf("%i. %s\n", i + 1, systems[i].ToString(true));
				}
				continue;
			}

			if (strcmp(message, "ban") == 0)
			{
				printf("Enter IP to ban.  You can use * as a wildcard\n");
				Gets(message, sizeof(message));
				server->AddToBanList(message);
				printf("IP %s added to ban list.\n", message);

				continue;
			}


			// Message now holds what we want to broadcast
			char message2[2048];
			// Append Server: to the message so clients know that it ORIGINATED from the server
			// All messages to all clients come from the server either directly or by being
			// relayed from other clients
			message2[0] = 0;
			const static char prefix[] = "Server: ";
			strncpy(message2, prefix, sizeof(message2));
			strncat(message2, message, sizeof(message2) - strlen(prefix) - 1);

			// message2 is the data to send
			// strlen(message2)+1 is to send the null terminator
			// HIGH_PRIORITY doesn't actually matter here because we don't use any other priority
			// RELIABLE_ORDERED means make sure the message arrives in the right order
			// We arbitrarily pick 0 for the ordering stream
			// RakNet::UNASSIGNED_SYSTEM_ADDRESS means don't exclude anyone from the broadcast
			// true means broadcast the message to everyone connected
			server->Send(message2, (const int)strlen(message2) + 1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
		}

		// Get a packet from either the server or the client

		for (p = server->Receive(); p; server->DeallocatePacket(p), p = server->Receive())
		{
			// We got a packet, get the identifier with our handy function
			packetIdentifier = GetPacketIdentifier(p);

			// Check if this is a network message packet
			switch (packetIdentifier)
			{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				printf("ID_DISCONNECTION_NOTIFICATION from %s\n", p->systemAddress.ToString(true));;
				break;


			case ID_NEW_INCOMING_CONNECTION:
				// Somebody connected.  We have their IP now
				printf("ID_NEW_INCOMING_CONNECTION from %s with GUID %s\n", p->systemAddress.ToString(true), p->guid.ToString());
				clientID = p->systemAddress; // Record the player ID of the client

				printf("Remote internal IDs:\n");
				for (int index = 0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++)
				{
					RakNet::SystemAddress internalId = server->GetInternalID(p->systemAddress, index);
					if (internalId != RakNet::UNASSIGNED_SYSTEM_ADDRESS)
					{
						printf("%i. %s\n", index + 1, internalId.ToString(true));
					}
				}

				break;

			case ID_INCOMPATIBLE_PROTOCOL_VERSION:
				printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
				break;

			case ID_CONNECTED_PING:
			case ID_UNCONNECTED_PING:
				printf("Ping from %s\n", p->systemAddress.ToString(true));
				break;

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

			default:
				// The server knows the static data of all clients, so we can prefix the message
				// With the name data
				printf("%s\n", p->data);

				// Relay the message.  We prefix the name for other clients.  This demonstrates
				// That messages can be changed on the server before being broadcast
				// Sending is the same as before
				sprintf(message, "%s", p->data);
				server->Send(message, (const int)strlen(message) + 1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->systemAddress, true);

				break;
			}

		}
	}

	server->Shutdown(300);
	// We're done with the network
	RakNet::RakPeerInterface::DestroyInstance(server);


}
コード例 #8
0
ファイル: netcode.cpp プロジェクト: xboxxxxd/sc4multi
// Handles all networking events
DWORD WINAPI HandleNetworking( LPVOID )
{
    // Create RakNet interfaces
    RakNet::RakPeerInterface *peer;
    RakNet::Packet *packet;

    // Initialize networking
    peer = RakNet::RakPeerInterface::GetInstance();

    // Rev up your engines
    RakNet::SocketDescriptor sd( 0, "127.0.0.1" );
    peer->Startup( 1, &sd, 1 );

    // GO GO GO
    RakNet::ConnectionAttemptResult attempt = peer->Connect( "127.0.0.1", 5187, NULL, 0 );

    // Success?
    if( attempt != RakNet::CONNECTION_ATTEMPT_STARTED )
    {
        // Nope
        switch( attempt )
        {
        // None of these should happen, EVER.
        case RakNet::ALREADY_CONNECTED_TO_ENDPOINT:
            MessageBoxA
            (
                NULL,
                "A connection attempt was made to a server we're already connected to.\nPlease contact a developer.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        case RakNet::CANNOT_RESOLVE_DOMAIN_NAME:
            MessageBoxA
            (
                NULL,
                "The given domain name could not be resolved.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        case RakNet::CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS:
            MessageBoxA
            (
                NULL,
                "Two connection attempts were being made at once by SC4Multi.\nPlease contact a developer.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        case RakNet::INVALID_PARAMETER:
            MessageBoxA
            (
                NULL,
                "An invalid parameter was passed by SC4Multi. Please contact a developer.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        case RakNet::SECURITY_INITIALIZATION_FAILED:
            MessageBoxA
            (
                NULL,
                "Security initialization failed. Something is terribly wrong,\nplease contact a developer.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        default:
            MessageBoxA
            (
                NULL,
                "Something went wrong during network initialization,\nand we don't know what.",
                "SC4Multi -- Network Error",
                MB_OK | MB_ICONERROR
            );
            break;
        }

        // Terminate via ugly hacks
        exit( 1 );
    }

    // Forever and ever and ever and ever and ever and...
    while( isRunning )
    {
        // If there are any packets, read it
        for( packet = peer->Receive(); packet; peer->DeallocatePacket( packet ), packet = peer->Receive() )
        {
            // Get the packet type ID
            switch( packet->data[0] )
            {
            case ID_REMOTE_DISCONNECTION_NOTIFICATION:
                MessageBoxA( NULL, "Other client quit", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_REMOTE_CONNECTION_LOST:
                MessageBoxA( NULL, "Other client timeout", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_REMOTE_NEW_INCOMING_CONNECTION:
                MessageBoxA( NULL, "Other client connection", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_CONNECTION_REQUEST_ACCEPTED:
            {
                MessageBoxA( NULL, "Our connection succeeded", "SC4Multi", MB_OK | MB_ICONINFORMATION );

                // Read the machine GUID generated by Windows
                char guid_net[255];
                bool isGuidNull = false;
                {
                    // Create a wide-char GUID buffer
                    wchar_t guid[255];

                    // Registry stuff
                    HKEY hKey    = 0;
                    DWORD dwType = 0;

                    // Get the size of our buffer
                    DWORD dwBufSize = sizeof( guid );

                    // Define the subkey
                    const wchar_t* subkey = L"Software\\Microsoft\\Cryptography";

                    // Open the registry
                    if( RegOpenKey( HKEY_LOCAL_MACHINE, subkey, &hKey ) == ERROR_SUCCESS )
                    {
                        // We're looking for a string
                        dwType = REG_SZ;

                        // Read to our buffer
                        if( !RegQueryValueEx( hKey, L"MachineGuid", 0, &dwType, (BYTE *)guid, &dwBufSize ) == ERROR_SUCCESS )
                        {
                            // Fall back to a null GUID
                            isGuidNull = true;
                        }
                        else
                        {
                            // Convert the wide char buffer into a char buffer
                            wcstombs( guid_net, guid, 255 );
                        }
                    }
                    else
                    {
                        // Fall back to a null GUID
                        isGuidNull = true;
                    }
                }

                // Initialize a bitstream
                RakNet::BitStream bsOut;

                // Send our user data to the server
                {
                    // Packet ID
                    bsOut.Write( (RakNet::MessageID)ID_SC4_CONNECTION_DATA );

                    // Nickname
                    bsOut.Write( "Stormeus" );

                    // Unique GUID, or a null one
                    if( isGuidNull )
                        bsOut.Write( 0 );
                    else
                    {
#ifdef DEBUG
                        MessageBoxA( NULL, guid_net, "SC4Multi -- GUID", MB_ICONINFORMATION | MB_OK );
#endif

                        bsOut.Write( guid_net );
                    }

                    // City taken
                    bsOut.Write( "Unknown City" );
                }

                // Priority shipping to the server
                peer->Send
                (
                    &bsOut,
                    HIGH_PRIORITY,
                    RELIABLE_ORDERED,
                    0,
                    packet->systemAddress,
                    false
                );

                break;
            }
            case ID_NEW_INCOMING_CONNECTION:
                MessageBoxA( NULL, "Incoming connection", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_NO_FREE_INCOMING_CONNECTIONS:
                MessageBoxA( NULL, "Server is full", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_DISCONNECTION_NOTIFICATION:
                MessageBoxA( NULL, "We disconnected", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            case ID_CONNECTION_LOST:
                MessageBoxA( NULL, "We lost connection", "SC4Multi", MB_OK | MB_ICONINFORMATION );
                break;
            }
        }
    }

    // Destroy this instance
    RakNet::RakPeerInterface::DestroyInstance( peer );

    // And we're done here.
    MessageBoxA( NULL, "Destroyed RakNet instance.", "SC4Multi -- Networking Debug", MB_OK | MB_ICONEXCLAMATION );

    return 1;
}
コード例 #9
0
ファイル: Video.cpp プロジェクト: darcyg/RakNet-Demo
void Video::run(const char* ip) {
	unsigned int maxConnectionsAllowed = 1;
	unsigned int maxPlayersPerServer = 1;
	unsigned short serverPort = 7000;

	RakNet::RakPeerInterface *rakPeer = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor socketDescriptor(serverPort, 0);

	if (rakPeer->Startup(maxConnectionsAllowed, &socketDescriptor, 1) != RakNet::RAKNET_STARTED) {
		std::cerr << "Startup fail:" << std::endl;
		RakNet::RakPeerInterface::DestroyInstance(rakPeer);
		return;
	}

	rakPeer->SetMaximumIncomingConnections(maxPlayersPerServer);

	RakNet::Packet *packet;
	unsigned char typeId;
	bool connected = false;
	char key;

	RakNet::SystemAddress address;

	if (ip) {
		std::cout << "Connect: " << ip << std::endl;
		rakPeer->Connect(ip, serverPort, 0, 0);
	}

	cv::namedWindow("MyVideo", CV_WINDOW_AUTOSIZE | CV_GUI_NORMAL);
	cv::createTrackbar("AlphaTrackbar", "MyVideo", &alpha_slider, 100);

	capture.open(0);
	if (!capture.isOpened()) {
		std::cout << "Capture open fail" << std::endl;
		return;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH, 320);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
	capture.set(CV_CAP_PROP_FOURCC, CV_FOURCC('X', '2', '6', '4'));

	cv::namedWindow("RemoteVideo", 1);

	while (1) {
		const time_t t = time(NULL);
		struct tm* current_time = localtime(&t);
		std::cout << "current time is " << current_time->tm_sec << std::endl;

		cv::Mat frame;
		capture.read(frame);
		cv::imshow("MyVideo", frame);

		packet = rakPeer->Receive();
		if (packet) {
			RakNet::BitStream bitStream(packet->data, packet->length, false);

			bitStream.Read(typeId);
			switch (typeId) {
				case ID_CONNECTION_REQUEST_ACCEPTED:
				{
					std::cout << "ID_CONNECTION_REQUEST_ACCEPTED" << ip << std::endl;
					address = packet->systemAddress;
					connected = true;
					break;
				}
				case ID_NEW_INCOMING_CONNECTION:
				{
					std::cout << "ID_NEW_INCOMING_CONNECTION" << ip << std::endl;
					address = packet->systemAddress;
					connected = true;
					break;
				}
				case ID_DISCONNECTION_NOTIFICATION:
				{
					connected = false;
					break;
				}
				case ID_CONNECTION_LOST:
				{
					connected = false;
					break;
				}
				case ID_USER_PACKET_ENUM:
				{					
					int cols, rows, type, channels, size;
					
					bitStream.Read(cols);
					bitStream.Read(rows);
					bitStream.Read(type);
					bitStream.Read(channels);
					bitStream.Read(size);
					
					char* data = new char[size];
					bitStream.Read(data, size);
					
					cv::Mat mat(cols, rows, type, (uchar*)data);
							
					cv::imshow("RemoteVideo", mat.reshape(channels, rows));
					
					delete data;
					break;
				}
				default:
					break;
			}
			rakPeer->DeallocatePacket(packet);
		}

		if (connected) {
			int size = frame.total()*frame.elemSize();

			RakNet::BitStream sendStream;
			sendStream.Write((RakNet::MessageID)ID_USER_PACKET_ENUM);
			sendStream.Write(frame.cols);
			sendStream.Write(frame.rows);
			sendStream.Write((int)frame.type());
			sendStream.Write(frame.channels());
			sendStream.Write(size);
			sendStream.Write((const char *)frame.data, size);

			rakPeer->Send(&sendStream, LOW_PRIORITY, UNRELIABLE_SEQUENCED, 0, address, false);
			//rakPeer->Send(&sendStream, IMMEDIATE_PRIORITY, UNRELIABLE_SEQUENCED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
		}
		key = cvWaitKey(10);
		if (char(key) == 27) {
			break;
		}
	}

	rakPeer->Shutdown(300);
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);

	cv::destroyAllWindows();
}