public void StartServer(ushort port, string password, bool occasionalPing = true, ushort maxConnection = 4, uint unrealiableTimeout = 1000) { server = RakPeerInterface.GetInstance(); server.SetIncomingPassword(password, password.Length);// "Rumpelstiltskin" server.SetTimeoutTime(30000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); p = new Packet(); SystemAddress clientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; SocketDescriptor socketDesc = new SocketDescriptor(port, ""); StartupResult result = server.Startup(maxConnection, socketDesc, 1); server.SetMaximumIncomingConnections(maxConnection); if (result != StartupResult.RAKNET_STARTED) { MessageBox("Server failed to start. Terminating."); } else { MessageBox("Server start successfully"); } server.SetOccasionalPing(occasionalPing); server.SetUnreliableTimeout(unrealiableTimeout); StringBuilder ipsb = new StringBuilder(); for (int i = 0; i < server.GetNumberOfAddresses(); i++) { SystemAddress sa = server.GetInternalID(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, i); ipsb.Append(string.Format("{0}. {1}", i + 1, sa.ToString(false))); } ServerIP = ipsb.ToString(); GUID = server.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString(); lis = new Thread(Listening); lis.Start(); }
static GameServer() { using (SocketDescriptor socketDescriptor = new SocketDescriptor()) { socketDescriptor.port = ServerOptions.Port; StartupResult res = ServerInterface.Startup(ServerOptions.Slots, socketDescriptor, 1); if (res == StartupResult.RAKNET_STARTED) { Logger.Log("Server starts RakNet on port " + ServerOptions.Port); } else { throw new Exception("RakNet startup failed: " + res.ToString()); } ServerInterface.SetMaximumIncomingConnections(ServerOptions.Slots); ServerInterface.SetOccasionalPing(true); if (ServerOptions.Password != null) { string pwStr = Convert.ToBase64String(ServerOptions.Password.ToArray()); ServerInterface.SetIncomingPassword(pwStr, pwStr.Length); } } }
IEnumerator connectToNATFacilitatorTest() { StartupResult startResult = rakPeerTest.Startup(2, new SocketDescriptor(), 1); if (startResult != StartupResult.RAKNET_STARTED) { Debug.Log("Failed to initialize network interface 2: " + startResult.ToString()); yield break; } ConnectionAttemptResult connectResult = rakPeerTest.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0); if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { Debug.Log("Failed to initialize connection to NAT Facilitator 2: " + connectResult.ToString()); yield break; } Packet packet; while ((packet = rakPeerTest.Receive()) == null) { yield return(new WaitForEndOfFrame()); } if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { Debug.Log("Failed to connect to NAT Facilitator 2: " + ((DefaultMessageIDTypes)packet.data[0])); yield break; } guidTest = rakPeerTest.GetMyGUID().g.ToString(); Debug.Log("Connected 2: " + guidTest); facilitatorSystemAddressTest = packet.systemAddress; externalIP = rakPeerTest.GetExternalID(packet.systemAddress).ToString(false); rakPeerTest.SetMaximumIncomingConnections(2); if (firstTimeConnectTest) { firstTimeConnectTest = false; natPunchthroughClientTest = new NatPunchthroughClient(); rakPeerTest.AttachPlugin(natPunchthroughClientTest); natPunchthroughClientTest.FindRouterPortStride(facilitatorSystemAddressTest); } else { StartCoroutine("waitForIncomingNATPunchThroughOnServerTest"); } connectedToFacTest = true; isReadyTest = true; }
public StartupResult Startup(ushort port, ushort maxConnect) { _Socket = new SocketDescriptor(port, ""); StartupResult result = _peer.Startup(maxConnect, _Socket, 1); _peer.SetMaximumIncomingConnections(maxConnect); Log.Info("RakPeerInterface.Startup(" + port + ")" + result); if (result == StartupResult.RAKNET_STARTED) { ProcessMessage(); } return(result); }
private void Initialize(ushort?serverPort, ushort maxConnections) { try { IsRunning = true; _logger.Info("transports.raknet", "starting raknet transport " + _type); _peer = RakPeerInterface.GetInstance(); var socketDescriptor = serverPort.HasValue ? new SocketDescriptor(serverPort.Value, null) : new SocketDescriptor(); var startupResult = _peer.Startup(maxConnections, socketDescriptor, 1); if (startupResult != StartupResult.RAKNET_STARTED) { throw new InvalidOperationException("Couldn't start raknet peer :" + startupResult); } _peer.SetMaximumIncomingConnections(maxConnections); } catch (Exception e) { throw new InvalidOperationException("Failed to initialize Raknet", e); } }
/** * Called on the server to start listening for clients trying to punch through */ public void startListeningForPunchthrough(Action <int> onHolePunched) { this.onHolePunched = onHolePunched; rakPeer.SetMaximumIncomingConnections(2); StartCoroutine(waitForIncomingNATPunchThroughOnServer(onHolePunched)); }
static void Main(string[] args) { if (!File.Exists("RakNet.dll")) { Console.WriteLine("The SWIG build of the DLL has not been copied to the executable directory\nCopy from Swig/SwigWindowsCSharpSample/SwigTestApp/bin/X86/Debug/RakNet.dll to\nSwigWindowsCSharpSample/SwigTestApp/bin/Debug/RakNet.dll\nPress enter to quit."); Console.Read(); return; } try { RakString dllCallTest = new RakString(); } catch (Exception e) { Console.WriteLine("DLL issue\nMake sure RakNetWrap.cxx is included in the DLL project.\nPress enter to quit."); Console.Read(); return; } Packet testPacket; int loopNumber; BitStream stringTestSendBitStream = new BitStream(); BitStream rakStringTestSendBitStream = new BitStream(); BitStream receiveBitStream = new BitStream(); String holdingString; TimeSpan startTimeSpan; RakString rakStringTest = new RakString(); RakPeerInterface testClient = RakPeer.GetInstance(); testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1); RakPeerInterface testServer = RakPeer.GetInstance(); testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1); testServer.SetMaximumIncomingConnections(1); Console.WriteLine("Send and receive loop using BitStream.\nBitStream read done into RakString"); testClient.Connect("127.0.0.1", 60001, "", 0); String sendString = "The test string"; stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); stringTestSendBitStream.Write(sendString); RakString testRakString = new RakString("Test RakString"); rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); rakStringTestSendBitStream.Write(testRakString); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(rakStringTest); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String()); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } Console.WriteLine("String send and receive loop using BitStream.\nBitStream read done into String"); SystemAddress[] remoteSystems; ushort numberOfSystems = 1; testServer.GetConnectionList(out remoteSystems, ref numberOfSystems); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(out holdingString); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + holdingString); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } //If RakString is not freed before program exit it will crash rakStringTest.Dispose(); testRakString.Dispose(); RakPeer.DestroyInstance(testClient); RakPeer.DestroyInstance(testServer); Console.WriteLine("Demo complete. Press Enter."); Console.Read(); }
IEnumerator connectToNATFacilitator() { StartupResult startResult = rakPeer.Startup(2, new SocketDescriptor(), 1); if (startResult != StartupResult.RAKNET_STARTED) { NATNetworkManager_PHP.DisplayLog("Failed to initialize network interface: " + startResult.ToString()); yield break; } ConnectionAttemptResult connectResult = rakPeer.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0); if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED) { NATNetworkManager_PHP.DisplayLog("Failed to initialize connection to NAT Facilitator: " + connectResult.ToString()); yield break; } Packet packet; while ((packet = rakPeer.Receive()) == null) { yield return(new WaitForEndOfFrame()); } if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { NATNetworkManager_PHP.DisplayLog("Failed to connect to NAT Facilitator: " + ((DefaultMessageIDTypes)packet.data[0])); NATNetworkManager_PHP.RefreshInfo(); yield break; } guid = rakPeer.GetMyGUID().g.ToString(); Debug.Log("Connected: " + guid); externalIP = rakPeer.GetExternalID(packet.systemAddress).ToString(false); NATNetworkManager_PHP.RefreshInfo(); //if (firstTimeConnect) { // firstTimeConnect = false; natPunchthroughClient = new NatPunchthroughClient(); rakPeer.AttachPlugin(natPunchthroughClient); natPunchthroughClient.FindRouterPortStride(packet.systemAddress); facilitatorSystemAddress = packet.systemAddress; /*} else { * rakPeer.AttachPlugin (natPunchthroughClient); * //if (!facilitatorSystemAddress.EqualsExcludingPort(packet.systemAddress)) { * natPunchthroughClient.FindRouterPortStride (packet.systemAddress); * //} * facilitatorSystemAddress = packet.systemAddress; * }*/ if (NetworkServer.active && NATNetworkManager_PHP.singleton.myRoom.isNetGame) { StartCoroutine("waitForIncomingNATPunchThroughOnServer"); } if (string.IsNullOrEmpty(guid)) { NATNetworkManager_PHP.DisplayLog("GUID IS NULL OR EMPTY"); } else { NATNetworkManager_PHP.singleton.StartCoroutine("setNewGUID", guid); } NATNetworkManager_PHP.connectedToFac = true; rakPeer.SetMaximumIncomingConnections(2); isReady = true; }
// Use this for initialization void Start() { try { RakString dllCallTest = new RakString(); } catch (Exception e) { Debug.Log("DLL issue\nAdd SwigOutput/CplusDLLIncludes/RakNetWrap.cxx to the project\nDLL_Swig/RakNet.sln and rebuild.\nPress enter to quit."); return; } Packet testPacket; int loopNumber; RakNet.BitStream stringTestSendBitStream = new RakNet.BitStream(); RakNet.BitStream rakStringTestSendBitStream = new RakNet.BitStream(); RakNet.BitStream receiveBitStream = new RakNet.BitStream(); String holdingString; TimeSpan startTimeSpan; RakString rakStringTest = new RakString(); RakPeerInterface testClient = RakPeer.GetInstance(); testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1); RakPeerInterface testServer = RakPeer.GetInstance(); testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1); testServer.SetMaximumIncomingConnections(1); Console.WriteLine("Send and receive loop using BitStream.\nBitStream read done into RakString"); testClient.Connect("127.0.0.1", 60001, "", 0); String sendString = "The test string"; stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); stringTestSendBitStream.Write(sendString); RakString testRakString = new RakString("Test RakString"); rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); rakStringTestSendBitStream.Write(testRakString); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(rakStringTest); Debug.Log("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String()); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } Debug.Log("String send and receive loop using BitStream.\nBitStream read done into String"); SystemAddress[] remoteSystems; ushort numberOfSystems = 1; testServer.GetConnectionList(out remoteSystems, ref numberOfSystems); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(out holdingString); Debug.Log("Loop number: " + loopNumber + "\nData: " + holdingString); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); SystemAddress sa = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } //If RakString is not freed before program exit it will crash rakStringTest.Dispose(); testRakString.Dispose(); RakPeer.DestroyInstance(testClient); RakPeer.DestroyInstance(testServer); Debug.Log("Demo complete. Press Enter."); }
static int Main(string[] args) { char ch; string userInput; rakPeer = RakNetworkFactory.GetRakPeerInterface(); rakPeer.AttachPlugin(replicaManager); rakPeer.SetNetworkIDManager(networkIDManager); replicaManager.SetAutoParticipateNewConnections(true); replicaManager.SetAutoConstructToNewParticipants(true); replicaManager.SetAutoSerializeInScope(true); replicaManager.SetReceiveConstructionCB(IntPtr.Zero, ConstructionCB); replicaManager.SetDownloadCompleteCB(IntPtr.Zero, SendDownloadCompleteCB, IntPtr.Zero, ReceiveDownloadCompleteCB); StringTable.Instance().AddString("Player", true); StringTable.Instance().AddString("Monster", true); Console.Write("Demonstration of ReplicaManager for client / server\n"); Console.Write("The replica manager provides a framework to make it easier to synchronize\n"); Console.Write("object creation, destruction, and member object updates\n"); Console.Write("Difficulty: Intermediate\n\n"); Console.Write("Run as (s)erver or (c)lient? "); userInput = Console.ReadLine(); if (userInput[0] == 's' || userInput[0] == 'S') { isServer = true; SocketDescriptor socketDescriptor = new SocketDescriptor(60000, string.Empty); rakPeer.Startup(8, 0, new SocketDescriptor[] { socketDescriptor }, 1); rakPeer.SetMaximumIncomingConnections(8); Console.Write("Server started.\n"); } else { isServer = false; SocketDescriptor socketDescriptor = new SocketDescriptor(); rakPeer.Startup(1, 0, new SocketDescriptor[] { socketDescriptor }, 1); Console.Write("Enter IP to connect to: "); userInput = Console.ReadLine(); if (userInput.Equals(string.Empty)) { userInput = "127.0.0.1"; Console.Write("{0}\n", userInput); } if (!rakPeer.Connect(userInput, 60000, string.Empty, 0)) { Console.Write("Connect call failed!\n"); return 1; } Console.Write("Connecting...\n"); } // The network ID manager will automatically index pointers of object instance NetworkIDObject if // SetIsNetworkIDAuthority is called with true. Otherwise, it will rely on another system setting the IDs networkIDManager.SetIsNetworkIDAuthority(isServer); Console.Write("Commands:\n(Q)uit\n(Space) Show status\n(R)andomize health and position\n"); if (isServer) { Console.Write("Toggle (M)onster\nToggle (p)layer\n"); Console.Write("Toggle (S)cope of player\n"); } Packet p; while (true) { p = rakPeer.Receive(); while (p != null) { byte[] data = p.data; // The access to data member had better reduce it. Copying occurs by this. if (data[0] == RakNetBindings.ID_DISCONNECTION_NOTIFICATION || data[0] == RakNetBindings.ID_CONNECTION_LOST) { if (isServer) { Console.Write("Server connection lost. Deleting objects\n"); if (monster != null) { monster.Dispose(); } if (player != null) { player.Dispose(); } } } rakPeer.DeallocatePacket(p); p = rakPeer.Receive(); } if (_kbhit() != 0) { ch = Console.ReadKey(true).KeyChar; if (ch == 'q' || ch == 'Q') { Console.Write("Quitting.\n"); break; } else if (ch == ' ') ShowStatus(monster, player); else if (ch == 'r' || ch == 'R') { if (player != null) { player.health = (int)RakNetBindings.randomMT(); player.position = (int)RakNetBindings.randomMT(); replicaManager.SignalSerializeNeeded(player.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } if (monster != null) { monster.health = (int)RakNetBindings.randomMT(); monster.position = (int)RakNetBindings.randomMT(); replicaManager.SignalSerializeNeeded(monster.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } Console.Write("Randomized player and monster health and position\n"); ShowStatus(monster, player); } else if (isServer) { if (ch == 'm' || ch == 'M') { if (monster == null) { Console.Write("Creating monster\n"); monster = new Monster(); } else { monster.Dispose(); Console.Write("Deleted monster\n"); monster = null; } } else if (ch == 'p' || ch == 'P') { if (player == null) { Console.Write("Creating player\n"); player = new Player(); } else { player.Dispose(); Console.Write("Deleted player\n"); player = null; } } else if (ch == 's' || ch == 'S') { if (player != null) { bool currentScope; currentScope = replicaManager.IsInScope(player.replica, rakPeer.GetSystemAddressFromIndex(0)); if (currentScope == false) Console.Write("Setting scope for player to true for all remote systems.\n"); else Console.Write("Setting scope for player to false for all remote systems.\n"); replicaManager.SetScope(player.replica, !currentScope, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } else { Console.Write("No player to set scope for\n"); } } } } System.Threading.Thread.Sleep(30); } if (monster != null) monster.Dispose(); if (player != null) player.Dispose(); RakNetworkFactory.DestroyRakPeerInterface(rakPeer); return 1; }
static void Main(string[] args) { Packet testPacket; int loopNumber; BitStream stringTestSendBitStream = new BitStream(); BitStream rakStringTestSendBitStream = new BitStream(); BitStream receiveBitStream = new BitStream(); String holdingString; TimeSpan startTimeSpan; RakString rakStringTest = new RakString(); RakPeerInterface testClient = RakPeer.GetInstance(); testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1); RakPeerInterface testServer = RakPeer.GetInstance(); testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1); testServer.SetMaximumIncomingConnections(1); Console.WriteLine("Press enter to start RakString send and receive loop using BitStream.\nBitStream read done into RakString"); Console.WriteLine("Loop will run for 15 seconds"); Console.ReadLine(); testClient.Connect("127.0.0.1", 60001, "", 0); String sendString = "The test string"; stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); stringTestSendBitStream.Write(sendString); RakString testRakString = new RakString("Test RakString"); rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); rakStringTestSendBitStream.Write(testRakString); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 15 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(rakStringTest); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String()); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } Console.WriteLine("Press enter to start String send and receive loop using BitStream.\nBitStream read done into String"); Console.WriteLine("Loop will run for 15 seconds"); Console.ReadLine(); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 15 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(out holdingString); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + holdingString); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } //If RakString is not freed before program exit it will crash rakStringTest.Dispose(); testRakString.Dispose(); RakPeer.DestroyInstance(testClient); RakPeer.DestroyInstance(testServer); Console.WriteLine("Demo complete. Press Enter."); Console.Read(); }
static void Main(string[] args) { RakNetStatistics rss = new RakNetStatistics(); RakPeerInterface server = RakPeerInterface.GetInstance(); server.SetIncomingPassword("Rumpelstiltskin", "Rumpelstiltskin".Length); server.SetTimeoutTime(30000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS); Packet p = new Packet(); RakNet.SystemAddress clientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; byte packetIdentifier; bool isServer = true; string serverPort; Console.WriteLine("Enter the client port to listen on"); serverPort = Console.ReadLine(); if (serverPort.Length == 0) { serverPort = "1234"; } Console.WriteLine("Starting server"); RakNet.SocketDescriptor socketDescriptors = new SocketDescriptor(Convert.ToUInt16(serverPort), "0"); socketDescriptors.port = Convert.ToUInt16(serverPort); socketDescriptors.socketFamily = AF_INET; StartupResult sar = server.Startup(4, socketDescriptors, 1); if (sar != StartupResult.RAKNET_STARTED) { Console.WriteLine("Error starting server"); } server.SetMaximumIncomingConnections(4); System.Threading.Thread.Sleep(1000); server.SetOccasionalPing(true); server.SetUnreliableTimeout(1000); for (int i = 0; i < server.GetNumberOfAddresses(); i++) { SystemAddress sa = server.GetInternalID(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, i); Console.WriteLine((i + 1).ToString() + ". " + sa.ToString() + "(LAN = " + sa.IsLANAddress() + ")"); } Console.WriteLine("My GUID is " + server.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString()); Console.WriteLine("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'pingip' to ping an ip address\n'ban' to ban an IP from connecting.\n'kick to kick the first connected player.\nType to talk."); string message; while (true) { System.Threading.Thread.Sleep(30); if (Console.KeyAvailable) { message = Console.ReadLine(); if (message == "quit") { Console.WriteLine("Quitting"); break; } if (message == "kick") { server.CloseConnection(clientID, true, 0); continue; } if (message == "stat") { rss = server.GetStatistics(server.GetSystemAddressFromIndex(0)); RakNet.RakNet.StatisticsToString(rss, out message, 2); Console.WriteLine(message); continue; } if (message == "ping") { server.Ping(clientID); continue; } if (message == "list") { SystemAddress[] systems = new SystemAddress[10]; ushort numCons = 10; server.GetConnectionList(out systems, ref numCons); for (int i = 0; i < numCons; i++) { Console.WriteLine((i + 1).ToString() + ". " + systems[i].ToString(true)); } continue; } if (message == "ban") { Console.WriteLine("'Enter IP to ban. You can use * as a wildcard"); message = Console.ReadLine(); server.AddToBanList(message); Console.WriteLine("IP " + message + " added to ban list."); continue; } string message2; message2 = "Server: " + message; server.Send(message2, message2.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); } for (p = server.Receive(); p != null; server.DeallocatePacket(p), p = server.Receive()) { packetIdentifier = GetPacketIdentifier(p); switch ((DefaultMessageIDTypes)packetIdentifier) { case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION: Console.WriteLine("ID_DISCONNECTION_NOTIFICATION from " + p.systemAddress.ToString(true)); break; case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION: Console.WriteLine("ID_NEW_INCOMING_CONNECTION from " + p.systemAddress.ToString(true) + "with GUID " + p.guid.ToString()); clientID = p.systemAddress; Console.WriteLine("Remote internal IDs: "); for (int index = 0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++) { SystemAddress internalId = server.GetInternalID(p.systemAddress, index); if (internalId != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS) { Console.WriteLine((index + 1).ToString() + ". " + internalId.ToString(true)); } } break; case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION: Console.WriteLine("ID_INCOMPATIBLE_PROTOCOL_VERSION"); break; case DefaultMessageIDTypes.ID_CONNECTED_PING: case DefaultMessageIDTypes.ID_UNCONNECTED_PING: Console.WriteLine("Ping from " + p.systemAddress.ToString(true)); break; case DefaultMessageIDTypes.ID_CONNECTION_LOST: Console.WriteLine("ID_CONNECTION_LOST from " + p.systemAddress.ToString(true)); break; default: Console.WriteLine(System.Text.Encoding.UTF8.GetString(p.data)); message = System.Text.Encoding.UTF8.GetString(p.data); server.Send(message, message.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true); break; } } } server.Shutdown(300); RakNet.RakPeerInterface.DestroyInstance(server); Console.Read(); }