static void Main(string[] args) { uint time; RakPeerInterface rakPeer1 = RakNetworkFactory.GetRakPeerInterface(); RakPeerInterface rakPeer2 = RakNetworkFactory.GetRakPeerInterface(); Console.Write("This project shows how to call member functions of your application object.\n"); Console.Write("instances.\n"); Console.Write("Difficulty: Advanced\n\n"); SocketDescriptor socketDescriptor = new SocketDescriptor(60000, string.Empty); rakPeer1.Startup(2, 0, new SocketDescriptor[] { socketDescriptor }, 1); socketDescriptor.port = 60001; rakPeer2.Startup(2, 0, new SocketDescriptor[] { socketDescriptor }, 1); rakPeer2.SetMaximumIncomingConnections(2); rakPeer1.Connect("127.0.0.1", 60001, string.Empty, 0); rakPeer2.RegisterClassMemberRPC(typeof(Apple).GetMethod("func1")); rakPeer2.RegisterClassMemberRPC(typeof(Apple).GetMethod("func2")); rakPeer2.RegisterClassMemberRPC(typeof(Apple).GetMethod("func3")); System.Threading.Thread.Sleep(250 * 4); // Please wait slightly longer. Apple apple = new GrannySmith(); time = RakNetBindings.GetTime(); Console.Write("Calling func1 of Apple base class with test string 1.\n"); // You should use interface. Clients should not know server implements. rakPeer1.RPC(typeof(Apple).GetMethod("func1"), GetBytes("test string 1"), (uint)(GetBytes("test string 1").Length * 8), PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true, 0, apple.GetNetworkID(), null); // Or you can pass full method name. // rakPeer1.RPC("ObjectMemberRPC.Apple.func1", GetBytes("test string 1"), (uint)(GetBytes("test string 1").Length * 8), PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true, 0, apple.GetNetworkID(), null); Console.Write("Calling func2 of Apple base class with test string 2.\n"); rakPeer1.RPC(typeof(Apple).GetMethod("func2"), GetBytes("test string 2"), (uint)(GetBytes("test string 2").Length * 8), PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true, 0, apple.GetNetworkID(), null); Console.Write("Calling func3 of Apple base class with no test string.\n"); rakPeer1.RPC(typeof(Apple).GetMethod("func3"), new byte[0], 0, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true, 0, apple.GetNetworkID(), null); while (RakNetBindings.GetTime() < time + 5000) { rakPeer1.DeallocatePacket(rakPeer1.Receive()); rakPeer2.DeallocatePacket(rakPeer2.Receive()); System.Threading.Thread.Sleep(30); } Console.Write("Sample complete. Press enter to quit."); Console.ReadLine(); RakNetworkFactory.DestroyRakPeerInterface(rakPeer1); RakNetworkFactory.DestroyRakPeerInterface(rakPeer2); }
static int Main(string[] args) { RakPeerInterface localSystem; Packet p; int systemType, threadSleepTimer; byte[] byteBlock = new byte[4096]; string input; StringBuilder buffer = new StringBuilder(4096); uint time, quitTime, nextStatsTime; uint packetsPerSecond = 0, bytesPerPacket = 0, num, index, bytesInPackets; uint lastSendTime; int sendMode = 0; int verbosityLevel; uint showStatsInterval; bool connectionCompleted, incomingConnectionCompleted; RakNetStatistics rss; Console.Write("Loopback performance test.\n"); Console.Write("This test measures the effective transfer rate of RakNetBindings.\n\n"); Console.Write("Instructions:\nStart 3 instances of this program.\n"); Console.Write("Press\n1. for the first instance (destination)\n2. for the second instance (relay)\n3. for the third instance (source).\n"); Console.Write("When the third instance is started the test will start.\n\n"); Console.Write("Difficulty: Intermediate\n\n"); Console.Write("Which instance is this? Enter 1, 2, or 3: "); input = Console.ReadLine(); systemType = input[0] - '0' - 1; if (systemType < 0 || systemType > 2) { Console.Write("Error, you must enter 1, 2, or 3.\nQuitting.\n"); return 1; } localSystem = RakNetworkFactory.GetRakPeerInterface(); /* Console.Write("Enter thread sleep timer:\n(0). Regular\n(1). High\n"); byteBlock = Console.ReadLine(); if (byteBlock[0]==0) { Console.Write("Defaulting to regular.\n"); threadSleepTimer=0; } else { if (byteBlock[0]<'0' || byteBlock[0]>'1') { Console.Write("Error, you must enter 0, or 1\n.Quitting.\n"); return 1; } threadSleepTimer=byteBlock[0]-'0'; } */ threadSleepTimer = 0; Console.Write("How many seconds do you want to run the test for?\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to 90 seconds\n"); quitTime = 90; } else quitTime = uint.Parse(input); Console.Write("Enter statistics verbosity level, 0=lowest, 2=highest\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to verbosity level 1\n"); verbosityLevel = 1; } else verbosityLevel = int.Parse(input); Console.Write("How frequently to show statistics, in seconds?\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to 5 seconds\n"); showStatsInterval = 5 * 1000; } else showStatsInterval = uint.Parse(input) * 1000; if (systemType == 0) { Console.Write("Initializing RakNetBindings...\n"); // Destination. Accept one connection and wait for further instructions. SocketDescriptor socketDescriptor = new SocketDescriptor(DESTINATION_SYSTEM_PORT, string.Empty); if (localSystem.Startup(1, threadSleepTimer, new SocketDescriptor[] { socketDescriptor }, 1) == false) { Console.Write("Failed to initialize RakNet!.\nQuitting\n"); return 1; } localSystem.SetMaximumIncomingConnections(1); Console.Write("Initialization complete. Destination system started and waiting...\n"); } else if (systemType == 1) { Console.Write("Enter MTU size to use. 576 for dialup, 1400 for AOL, 1492 otherwise.\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to 1492.\n"); localSystem.SetMTUSize(1492, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS); } else localSystem.SetMTUSize(int.Parse(input), RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS); Console.Write("What send mode to use for relays?\n"); Console.Write("(0). UNRELIABLE\n"); Console.Write("(1). UNRELIABLE_SEQUENCED\n"); Console.Write("(2). RELIABLE\n"); Console.Write("(3). RELIABLE_ORDERED\n"); Console.Write("(4). RELIABLE_SEQUENCED\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to RELIABLE\n"); sendMode = 2; } else { sendMode = int.Parse(input); if (sendMode < 0 || sendMode > 4) { Console.Write("Invalid send mode. Using UNRELIABLE\n"); sendMode = 0; } } Console.Write("Initializing RakNetBindings...\n"); // Relay. Accept one connection, initiate outgoing connection, wait for further instructions. SocketDescriptor socketDescriptor = new SocketDescriptor(RELAY_SYSTEM_PORT, string.Empty); if (localSystem.Startup(2, threadSleepTimer, new SocketDescriptor[] { socketDescriptor }, 1) == false) { Console.Write("Failed to initialize RakNet!.\nQuitting\n"); return 1; } localSystem.SetMaximumIncomingConnections(1); socketDescriptor.port = DESTINATION_SYSTEM_PORT; if (localSystem.Connect("127.0.0.1", DESTINATION_SYSTEM_PORT, string.Empty, 0) == false) { Console.Write("Connect call failed!.\nQuitting\n"); return 1; } Console.Write("Initialization complete. Relay system started.\nConnecting to destination and waiting for sender...\n"); } else { Console.Write("Enter MTU size to use. 576 for dialup, 1400 for AOL, 1492 otherwise.\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to 1492.\n"); localSystem.SetMTUSize(1492, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS); } else localSystem.SetMTUSize(int.Parse(input), RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS); Console.Write("How many packets do you wish to send per second?\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { #if DEBUG Console.Write("Defaulting to 1000\n"); packetsPerSecond = 1000; #else Console.Write("Defaulting to 10000\n"); packetsPerSecond=10000; #endif } else packetsPerSecond = uint.Parse(input); Console.Write("How many bytes per packet?\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to 400\n"); bytesPerPacket = 400; } else { bytesPerPacket = uint.Parse(input); if (bytesPerPacket > 4096) { Console.Write("Increase the array size of byteBlock to send more than 4096 bytes.\n"); bytesPerPacket = 4096; } } Console.Write("What send mode?\n"); Console.Write("(0). UNRELIABLE\n"); Console.Write("(1). UNRELIABLE_SEQUENCED\n"); Console.Write("(2). RELIABLE\n"); Console.Write("(3). RELIABLE_ORDERED\n"); Console.Write("(4). RELIABLE_SEQUENCED\n"); input = Console.ReadLine(); if (input.Equals(string.Empty)) { Console.Write("Defaulting to RELIABLE\n"); sendMode = 2; } else { sendMode = int.Parse(input); if (sendMode < 0 || sendMode > 4) { Console.Write("Invalid send mode. Using UNRELIABLE\n"); sendMode = 0; } } Console.Write("Initializing RakNetBindings...\n"); // Sender. Initiate outgoing connection to relay. SocketDescriptor socketDescriptor = new SocketDescriptor(SOURCE_SYSTEM_PORT, string.Empty); if (localSystem.Startup(1, threadSleepTimer, new SocketDescriptor[] { socketDescriptor }, 1) == false) { Console.Write("Failed to initialize RakNet!.\nQuitting\n"); return 1; } if (localSystem.Connect("127.0.0.1", RELAY_SYSTEM_PORT, string.Empty, 0) == false) { Console.Write("Connect call failed!.\nQuitting\n"); return 1; } Console.Write("Initialization complete. Sender system started. Connecting to relay...\n"); } connectionCompleted = false; incomingConnectionCompleted = false; time = RakNetBindings.GetTime(); lastSendTime = time; nextStatsTime = time + 2000; // First stat shows up in 2 seconds bytesInPackets = 0; while (time < quitTime || (connectionCompleted == false && incomingConnectionCompleted == false)) { time = RakNetBindings.GetTime(); // Parse messages while (true) { p = localSystem.Receive(); if (p != null) { bytesInPackets += p.length; BitStream inBitStream = new BitStream(p, false); byte packetIdentifier; inBitStream.Read(out packetIdentifier); inBitStream.ResetReadPointer(); switch (packetIdentifier) { case RakNetBindings.ID_CONNECTION_REQUEST_ACCEPTED: Console.Write("ID_CONNECTION_REQUEST_ACCEPTED.\n"); connectionCompleted = true; // Timer starts when a connection has completed if (systemType == 1 || systemType == 2) quitTime = quitTime * 1000 + time; break; case RakNetBindings.ID_DISCONNECTION_NOTIFICATION: // Connection lost normally Console.Write("ID_DISCONNECTION_NOTIFICATION.\n"); // connectionCompleted=false; break; case RakNetBindings.ID_NEW_INCOMING_CONNECTION: // Somebody connected. We have their IP now Console.Write("ID_NEW_INCOMING_CONNECTION.\n"); incomingConnectionCompleted = true; // Timer starts when a new connection has come in if (systemType == 0) quitTime = quitTime * 1000 + time; if (systemType == 1 && connectionCompleted == false) Console.Write("Warning, relay connection to destination has not completed yet.\n"); break; case RakNetBindings.ID_CONNECTION_LOST: // Couldn't deliver a reliable packet - i.e. the other system was abnormally // terminated Console.Write("ID_CONNECTION_LOST.\n"); // connectionCompleted=false; break; case RakNetBindings.ID_NO_FREE_INCOMING_CONNECTIONS: Console.Write("ID_NO_FREE_INCOMING_CONNECTIONS.\n"); break; default: // The relay system will relay all data with 255 as the first byte if (systemType == 1) { if (packetIdentifier == 255) { if (localSystem.Send(inBitStream, PacketPriority.HIGH_PRIORITY, (PacketReliability)sendMode, 0, p.systemAddress, true) == false) { Console.Write("Relay failed!\n"); } } else Console.Write("Got packet with ID {0}\n", packetIdentifier); } break; } } else break; localSystem.DeallocatePacket(p); } // Show stats. if (time > nextStatsTime && (connectionCompleted || incomingConnectionCompleted)) { Console.Write("\n* First connected system statistics:\n"); rss = localSystem.GetStatistics(localSystem.GetSystemAddressFromIndex(0)); RakNetBindings.StatisticsToString(rss, buffer, verbosityLevel); Console.Write("{0}", buffer.ToString()); if (systemType == 1) { rss = localSystem.GetStatistics(localSystem.GetSystemAddressFromIndex(1)); if (rss != null) { Console.Write("* Second connected system statistics:\n"); RakNetBindings.StatisticsToString(rss, buffer, verbosityLevel); Console.Write("{0}", buffer.ToString()); } } nextStatsTime = time + showStatsInterval; } // As the destination, we don't care if the connection is completed. Do nothing // As the relay, we relay packets if the connection is completed. // That is done when the packet arrives. // As the source, we start sending packets when the connection is completed. if (systemType == 2 && connectionCompleted) { // Number of packets to send is (float)(packetsPerSecond * (time - lastSendTime)) / 1000.0f; num = (packetsPerSecond * (uint)(time - lastSendTime)) / 1000; byteBlock[0] = 255; // Relay all data with an identifier of 255 for (index = 0; index < num; index++) { localSystem.Send(byteBlock, (int)bytesPerPacket, PacketPriority.HIGH_PRIORITY, (PacketReliability)sendMode, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } lastSendTime += (1000 * num) / packetsPerSecond; } System.Threading.Thread.Sleep(100); } Console.Write("Test duration elapsed. Final Stats:\n"); Console.Write("\n* First connected system statistics:\n"); rss = localSystem.GetStatistics(localSystem.GetSystemAddressFromIndex(0)); RakNetBindings.StatisticsToString(rss, buffer, 2); Console.Write("{0}", buffer.ToString()); if (systemType == 1) { rss = localSystem.GetStatistics(localSystem.GetSystemAddressFromIndex(1)); if (rss != null) { Console.Write("* Second connected system statistics:\n"); RakNetBindings.StatisticsToString(rss, buffer, 2); Console.Write("{0}", buffer.ToString()); } } Console.Write("Hit enter to continue.\n"); string buff; buff = Console.ReadLine(); RakNetworkFactory.DestroyRakPeerInterface(localSystem); return 0; }
public void Startup(ushort maxConnections, int threadSleepTimer, ushort port, PluginInterface[] plugins) { rakPeerInterface = RakNetworkFactory.GetRakPeerInterface(); foreach (PluginInterface plugin in plugins) { RakPeerInterface.AttachPlugin(plugin); } // Initialize the peer SocketDescriptor socketDescriptor = new SocketDescriptor(port, string.Empty); RakPeerInterface.Startup(maxConnections, threadSleepTimer, new SocketDescriptor[] {socketDescriptor}, 1); RakPeerInterface.SetMaximumIncomingConnections(maxConnections); binder = new RpcBinder(RakPeerInterface, registry, processorLocator.Processor); binder.Bind(); }
static void Main(string[] args) { char ch; bool isServer; LightweightDatabaseServer databaseServer = new LightweightDatabaseServer(); LightweightDatabaseClient databaseClient = new LightweightDatabaseClient(); RakPeerInterface rakPeer = RakNetworkFactory.GetRakPeerInterface(); string str; string columnName; string tableName = "", tablePassword = ""; Console.Write("(S)erver or (C)lient?\n"); ch = Console.ReadKey(true).KeyChar; if (ch == 's') { isServer = true; rakPeer.SetMaximumIncomingConnections(32); SocketDescriptor socketDescriptor = new SocketDescriptor(12345, string.Empty); rakPeer.Startup(32, 0, new SocketDescriptor[] { socketDescriptor }, 1); rakPeer.AttachPlugin(databaseServer); Console.Write("Server started\n"); Console.Write("(C)reate table\n"); Console.Write("(R)emove table\n"); } else { isServer = false; SocketDescriptor socketDescriptor = new SocketDescriptor(); rakPeer.Startup(1, 0, new SocketDescriptor[] { socketDescriptor }, 1); rakPeer.AttachPlugin(databaseClient); Console.Write("Client started\n"); Console.Write("Enter server IP: "); str = Console.ReadLine(); if (str.Equals(string.Empty)) str = "127.0.0.1"; Console.Write("Connecting to server.\n"); rakPeer.Connect(str, 12345, string.Empty, 0); Console.Write("(Q)uery table\n"); Console.Write("(U)pdate row\n"); Console.Write("(R)emove row\n"); } Console.Write("(E)xit\n"); Packet p; while (true) { p = rakPeer.Receive(); while (p != null) { byte[] data = p.data; if (data[0] == RakNetBindings.ID_DISCONNECTION_NOTIFICATION) Console.Write("ID_DISCONNECTION_NOTIFICATION\n"); else if (data[0] == RakNetBindings.ID_CONNECTION_LOST) Console.Write("ID_CONNECTION_LOST\n"); else if (data[0] == RakNetBindings.ID_NO_FREE_INCOMING_CONNECTIONS) Console.Write("ID_NO_FREE_INCOMING_CONNECTIONS\n"); else if (data[0] == RakNetBindings.ID_NEW_INCOMING_CONNECTION) Console.Write("ID_NEW_INCOMING_CONNECTION\n"); else if (data[0] == RakNetBindings.ID_CONNECTION_REQUEST_ACCEPTED) Console.Write("ID_CONNECTION_REQUEST_ACCEPTED\n"); else if (data[0] == RakNetBindings.ID_CONNECTION_ATTEMPT_FAILED) Console.Write("ID_CONNECTION_ATTEMPT_FAILED\n"); else if (data[0] == RakNetBindings.ID_DATABASE_UNKNOWN_TABLE) Console.Write("ID_DATABASE_UNKNOWN_TABLE\n"); else if (data[0] == RakNetBindings.ID_DATABASE_INCORRECT_PASSWORD) Console.Write("ID_DATABASE_INCORRECT_PASSWORD\n"); else if (data[0] == RakNetBindings.ID_DATABASE_QUERY_REPLY) { Console.Write("Incoming table:\n"); Table table = new Table(); byte[] serializedTable = new byte[data.Length - sizeof(byte)]; Array.Copy(data, sizeof(byte), serializedTable, 0, data.Length - sizeof(byte)); // ugly copy if (TableSerializer.DeserializeTable(serializedTable, (uint)serializedTable.Length, table)) { TableRowPage cur = table.GetListHead(); int i; Console.Write("Columns:\n"); for (i = 0; i < table.GetColumns().Size(); i++) { Console.Write("{0}. {1} : ", i + 1, table.GetColumns()[i].columnName); if (table.GetColumns()[i].columnType == Table.ColumnType.BINARY) Console.Write("BINARY"); else if (table.GetColumns()[i].columnType == Table.ColumnType.NUMERIC) Console.Write("NUMERIC"); else Console.Write("STRING"); Console.Write("\n"); } if (cur != null) Console.Write("Rows:\n"); else Console.Write("Table has no rows.\n"); while (cur != null) { for (i = 0; i < cur.size; i++) { StringBuilder sb = new StringBuilder(256); table.PrintRow(sb, sb.Capacity, ',', true, cur.GetData(i)); Console.Write("RowID {0}: {1}\n", cur.GetKey(i), sb.ToString()); } cur = cur.next; } } else Console.Write("Deserialization of table failed.\n"); } rakPeer.DeallocatePacket(p); p = rakPeer.Receive(); } if (_kbhit() != 0) { char _ch = Console.ReadKey(true).KeyChar; if (isServer) { if (_ch == 'c') { bool allowRemoteUpdate; bool allowRemoteQuery; bool allowRemoteRemove; string queryPassword = string.Empty; string updatePassword = string.Empty; string removePassword = string.Empty; bool oneRowPerSystemAddress = false; bool onlyUpdateOwnRows = false; bool removeRowOnPingFailure = false; bool removeRowOnDisconnect = false; bool autogenerateRowIDs; Console.Write("Enter name of table to create: "); tableName = Console.ReadLine(); if (tableName.Equals(string.Empty)) tableName = "Default Table"; Console.Write("Allow remote row updates? (y (Default) / n)\n"); if (Console.ReadKey(false).KeyChar == 'n') { Console.Write("\n"); allowRemoteUpdate = false; } else { Console.Write("\n"); allowRemoteUpdate = true; Console.Write("Enter remote update password (Enter for none): "); updatePassword = Console.ReadLine(); Console.Write("Only allow one row per uploading IP? (y (Default) / n)\n"); oneRowPerSystemAddress = (Console.ReadKey(false).KeyChar == 'n') == false; Console.Write("Only allow updates on rows created by that system? (y (Default) / n)\n"); onlyUpdateOwnRows = (Console.ReadKey(false).KeyChar == 'n') == false; Console.Write("Remove row if can't ping system? (y (Default) / n)\n"); removeRowOnPingFailure = (Console.ReadKey(false).KeyChar == 'n') == false; Console.Write("Remove row on system disconnect? (y / n (Default))\n"); removeRowOnDisconnect = (Console.ReadKey(false).KeyChar == 'y') == true; } Console.Write("Allow remote table queries? (y (Default) / n)\n"); if (Console.ReadKey(false).KeyChar == 'n') { Console.Write("\n"); allowRemoteQuery = false; } else { Console.Write("\n"); allowRemoteQuery = true; Console.Write("Enter remote table query password (Enter for none): "); queryPassword = Console.ReadLine(); } Console.Write("Allow remote row removal? (y (Default) / n)\n"); if (Console.ReadKey(false).KeyChar == 'n') { Console.Write("\n"); allowRemoteRemove = false; } else { Console.Write("\n"); allowRemoteRemove = true; Console.Write("Enter remote row removal password (Enter for none): "); removePassword = Console.ReadLine(); } Console.Write("Autogenerate row ids? (y (Default) / n)\n"); autogenerateRowIDs = (Console.ReadKey(false).KeyChar == 'n') == false; Table table; table = databaseServer.AddTable(tableName, allowRemoteUpdate, allowRemoteQuery, allowRemoteRemove, queryPassword, updatePassword, removePassword, oneRowPerSystemAddress, onlyUpdateOwnRows, removeRowOnPingFailure, removeRowOnDisconnect, autogenerateRowIDs); if (table != null) { Console.Write("Table {0} created.\n", tableName); while (true) { Console.Write("Enter name of new column\n"); Console.Write("Hit enter when done\n"); columnName = Console.ReadLine(); if (columnName.Equals(string.Empty)) break; Table.ColumnType columnType; Console.Write("Enter column type\n1=STRING\n2=NUMERIC\n3=BINARY\n"); str = Console.ReadLine(); if (str[0] == '1') columnType = Table.ColumnType.STRING; else if (str[0] == '2') columnType = Table.ColumnType.NUMERIC; else if (str[0] == '3') columnType = Table.ColumnType.BINARY; else { Console.Write("Defaulting to string\n"); columnType = Table.ColumnType.STRING; } table.AddColumn(columnName, columnType); Console.Write("{0} added.\n", columnName); } Console.Write("Done.\n"); } else Console.Write("Table {0} creation failed. Possibly already exists.\n", tableName); } else if (_ch == 'r') { Console.Write("Enter name of table to remove: "); str = Console.ReadLine(); if (str.Equals(string.Empty)) str = "Default Table"; if (databaseServer.RemoveTable(str)) Console.Write("Success\n"); else Console.Write("Table {0} not found\n", str); } } else { if (_ch == 'q' || _ch == 'u' || _ch == 'r') { Console.Write("Enter table name: "); tableName = Console.ReadLine(); if (tableName.Equals(string.Empty)) tableName = "Default Table"; Console.Write("Enter password (if any): "); tablePassword = Console.ReadLine(); } if (_ch == 'q') { // TODO - let the user enter filters, columns, and rows to return. databaseClient.QueryTable(tableName, tablePassword, null, 0, null, 0, null, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } else if (_ch == 'u') { RowUpdateMode updateMode; uint rowId; bool hasRowId; Console.Write("Enter row update mode\n1=update existing\n2=update or add\n3=add new\n"); str = Console.ReadLine(); if (str[0] == '1') { updateMode = RowUpdateMode.RUM_UPDATE_EXISTING_ROW; Console.Write("Updating existing row (You must enter a row ID).\n"); } else if (str[0] == '2') { updateMode = RowUpdateMode.RUM_UPDATE_OR_ADD_ROW; Console.Write("Updating existing row and adding\nnew row if existing row does not exist.\n"); } else { updateMode = RowUpdateMode.RUM_ADD_NEW_ROW; Console.Write("Adding new row.\n"); } Console.Write("Enter row ID (enter for none): "); str = Console.ReadLine(); if (!str.Equals(string.Empty)) { rowId = uint.Parse(str); hasRowId = true; } else { hasRowId = false; rowId = 0; } Console.Write("Enter cells\n"); byte numCellUpdates; DatabaseCellUpdates cellUpdates = new DatabaseCellUpdates(64); for (numCellUpdates = 0; numCellUpdates < 64; numCellUpdates++) { Console.Write("Enter column name (Enter when done): "); cellUpdates[numCellUpdates].columnName = Console.ReadLine(); if (cellUpdates[numCellUpdates].columnName.Equals(string.Empty)) break; Console.Write("Enter column type\n1=STRING\n2=NUMERIC\n3=BINARY\n"); str = Console.ReadLine(); if (str[0] == '1' || str.Equals(string.Empty)) { cellUpdates[numCellUpdates].columnType = Table.ColumnType.STRING; Console.Write("Enter string value: "); str = Console.ReadLine(); cellUpdates[numCellUpdates].cellValue.Set(str); } else if (str[0] == '2') { cellUpdates[numCellUpdates].columnType = Table.ColumnType.NUMERIC; Console.Write("Enter numeric value: "); str = Console.ReadLine(); cellUpdates[numCellUpdates].cellValue.Set(int.Parse(str)); } else { cellUpdates[numCellUpdates].columnType = Table.ColumnType.BINARY; // TODO - Pain in the ass to write this demo code Console.Write("TODO\n"); } } databaseClient.UpdateRow(tableName, tablePassword, updateMode, hasRowId, rowId, cellUpdates, numCellUpdates, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } else if (_ch == 'r') { uint rowId; Console.Write("Enter row ID to remove: "); str = Console.ReadLine(); rowId = uint.Parse(str); databaseClient.RemoveRow(tableName, tablePassword, rowId, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } } if (_ch == 'e') break; _ch = '\0'; } RakNetBindings.RakSleep(30); } rakPeer.Shutdown(100, 0); RakNetworkFactory.DestroyRakPeerInterface(rakPeer); }
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 int Main(string[] args) { // Pointers to the interfaces of our server and client. // Note we can easily have both in the same program RakPeerInterface client; RakPeerInterface server; bool b; string str; string serverPort, clientPort; uint quitTime; // Holds packets Packet p; Console.Write("A client / server sample showing how clients can broadcast offline packets\n"); Console.Write("to find active servers.\n"); Console.Write("Difficulty: Beginner\n\n"); Console.Write("Instructions:\nRun one or more servers on the same port.\nRun a client and it will get pongs from those servers.\n"); Console.Write("Run as (s)erver or (c)lient?\n"); str = Console.ReadLine(); if (str[0]=='s' || str[0]=='S') { client=null; server=RakNetworkFactory.GetRakPeerInterface(); // A server Console.Write("Enter the server port\n"); serverPort = Console.ReadLine(); if (serverPort.Equals(string.Empty)) serverPort = "60001"; Console.Write("Starting server.\n"); // The server has to be started to respond to pings. SocketDescriptor socketDescriptor = new SocketDescriptor(ushort.Parse(serverPort),string.Empty); b = server.Startup(2, 30, new SocketDescriptor[] { socketDescriptor }, 1); server.SetMaximumIncomingConnections(2); if (b) Console.Write("Server started, waiting for connections.\n"); else { Console.Write("Server failed to start. Terminating.\n"); Environment.Exit(1); } } else { client=RakNetworkFactory.GetRakPeerInterface(); server=null; // Get our input Console.Write("Enter the client port to listen on, or 0\n"); clientPort = Console.ReadLine(); if (clientPort.Equals(string.Empty)) clientPort = "60000"; Console.Write("Enter the port to ping\n"); serverPort = Console.ReadLine(); if (serverPort.Equals(string.Empty)) serverPort = "60001"; SocketDescriptor socketDescriptor = new SocketDescriptor(ushort.Parse(clientPort),string.Empty); client.Startup(1, 30, new SocketDescriptor[] { socketDescriptor }, 1); // Connecting the client is very simple. 0 means we don't care about // a connectionValidationInteger, and false for low priority threads // All 255's mean broadcast client.Ping("255.255.255.255", ushort.Parse(serverPort), true); Console.Write("Pinging\n"); } Console.Write("How many seconds to run this sample for?\n"); str = Console.ReadLine(); if (str.Equals(string.Empty)) { Console.Write("Defaulting to 5 seconds\n"); quitTime = RakNetBindings.GetTime() + 5000; } else quitTime = RakNetBindings.GetTime() + uint.Parse(str) * 1000; // Loop for input while (RakNetBindings.GetTime() < quitTime) { if (server != null) p = server.Receive(); else p = client.Receive(); if (p == null) { System.Threading.Thread.Sleep(30); continue; } if (server != null) server.DeallocatePacket(p); else { BitStream inBitStream = new BitStream(p, false); byte packetIdentifier; inBitStream.Read(out packetIdentifier); if (packetIdentifier == RakNetBindings.ID_PONG) { uint time; inBitStream.Read(out time); Console.Write("Got pong from {0} with time {1}\n", p.systemAddress.ToString(), RakNetBindings.GetTime() - time); } client.DeallocatePacket(p); } System.Threading.Thread.Sleep(30); } // We're done with the network if (server != null) RakNetworkFactory.DestroyRakPeerInterface(server); if (client != null) RakNetworkFactory.DestroyRakPeerInterface(client); return 0; }
static void Main(string[] args) { RakPeerInterface rakClient = RakNetworkFactory.GetRakPeerInterface(); RakPeerInterface rakServer = RakNetworkFactory.GetRakPeerInterface(); quit = false; string text; rakClient.RegisterAsRemoteProcedureCall(typeof(Program).GetMethod("clientRPC")); SocketDescriptor socketDescriptor = new SocketDescriptor(2000, string.Empty); if (!rakServer.Startup(1, 30, new SocketDescriptor[] { socketDescriptor }, 1)) { Console.Write("Start call failed!\n"); return; } rakServer.SetMaximumIncomingConnections(1); socketDescriptor.port = 2100; rakClient.Startup(1, 30, new SocketDescriptor[] { socketDescriptor }, 1); if (!rakClient.Connect("127.0.0.1", 2000, string.Empty, 0)) { Console.Write("Connect call failed\n"); return; } BitStream outgoingBitstream = new BitStream(); uint age; Console.Write("A sample on how to use RakNet's bitstream class\n"); Console.Write("Difficulty: Beginner\n\n"); Console.Write("Enter your name.\n"); text = Console.ReadLine(); if (text.Equals(string.Empty)) text = "Unnamed!"; outgoingBitstream.Write(text); Console.Write("Enter your age (numbers only).\n"); text = Console.ReadLine(); if (text.Equals(string.Empty)) age = 0; else age = uint.Parse(text); outgoingBitstream.WriteCompressed(age); Console.Write("Are you employed (y/n)?\n"); text = Console.ReadLine(); if (text == "y") { outgoingBitstream.Write(true); // Read some data into a struct EmploymentStruct employmentStruct; Console.Write("What is your salary (enter a number only)?\n"); text = Console.ReadLine(); employmentStruct.salary = int.Parse(text); Console.Write("How many years have you been employed (enter a number only)?\n"); text = Console.ReadLine(); employmentStruct.yearsEmployed = byte.Parse(text); // We can write structs to a bitstream but this is not portable due to: // 1. Different-endian CPUs // 2. Different 'padding' of structs depending on compiler, etc // The only safe way to send a struct is by using the BitStream // to write out every single member which you want to send. outgoingBitstream.Write(employmentStruct.salary); outgoingBitstream.Write(employmentStruct.yearsEmployed); // We're done writing to the struct } else { //Console.Write("Number of bits before [false]: %d\n", //outgoingBitstream.GetNumberOfBitsUsed() ); outgoingBitstream.Write(false); // Writing a bool takes 1 bit // We're done writing to the struct. Compare this to the example above - we wrote quite a bit less. } bool success = rakServer.RPC(typeof(Program).GetMethod("clientRPC"), outgoingBitstream, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true, 0, RakNetBindings.UNASSIGNED_NETWORK_ID, null); if (!success) Console.Write("RPC call failed\n"); while (!quit) { rakClient.DeallocatePacket(rakClient.Receive()); rakServer.DeallocatePacket(rakServer.Receive()); System.Threading.Thread.Sleep(30); } Console.Write("Press enter to quit\n"); Console.ReadLine(); rakClient.Shutdown(100, 0); rakServer.Shutdown(100, 0); // This is not necessary since on shutdown everything is unregistered. This is just here to show usage rakClient.UnregisterAsRemoteProcedureCall(typeof(Program).GetMethod("clientRPC")); RakNetworkFactory.DestroyRakPeerInterface(rakClient); RakNetworkFactory.DestroyRakPeerInterface(rakServer); }
static void Main(string[] args) { char ch; bool isServer; RakPeerInterface serverRakPeer = RakNetworkFactory.GetRakPeerInterface(); const int maxNumberOfClients = 2048; IList<Connection> clientConnections = new List<Connection>(maxNumberOfClients); const ushort portNum = 12345; int querySize = 1000; byte[] dummyData = new byte[querySize]; Random r = new Random(); r.NextBytes(dummyData); dummyData[0] = (byte)RakNetBindings.ID_USER_PACKET_ENUM; List<SystemAddress> incomingConnections = new List<SystemAddress>(maxNumberOfClients); Console.WriteLine("(S)erver or (C)lient?"); ch = Console.ReadKey(true).KeyChar; if (ch == 's') { isServer = true; serverRakPeer.SetMaximumIncomingConnections(maxNumberOfClients); SocketDescriptor socketDescriptor = new SocketDescriptor(portNum, string.Empty); serverRakPeer.Startup(maxNumberOfClients, 0, new SocketDescriptor[] { socketDescriptor }, 1); Console.WriteLine("Server started"); } else { isServer = false; Console.Write("Number of Clients: "); string numberOfClientsString = Console.ReadLine(); int numberOfClients = Convert.ToInt32(numberOfClientsString); Console.Write("Query size: "); string querySizeString = Console.ReadLine(); querySize = Convert.ToInt32(querySizeString); SocketDescriptor socketDescriptor = new SocketDescriptor(); for (int i = 0; i < numberOfClients; ++i) { RakPeerInterface clientRakPeer = RakNetworkFactory.GetRakPeerInterface(); clientRakPeer.Startup(1, 0, new SocketDescriptor[] { socketDescriptor }, 1); clientConnections.Add(new Connection(clientRakPeer, false)); } Console.WriteLine("Client started"); Console.Write("Enter server IP: "); string serverIP = Console.ReadLine(); Console.WriteLine("Connecting to server."); foreach (Connection clientConnection in clientConnections) { clientConnection.RakPeer.Connect(serverIP, portNum, string.Empty, 0); } } //Console.WriteLine("(E)xit"); uint lastLog = 0; while (true) { if (isServer) { Packet p = serverRakPeer.Receive(); if (p != null) { BitStream inBitStream = new BitStream(p, false); byte packetIdentifier; inBitStream.Read(out packetIdentifier); switch (packetIdentifier) { case RakNetBindings.ID_NEW_INCOMING_CONNECTION: Console.WriteLine("ID_NEW_INCOMING_CONNECTION"); //incomingConnections.Add(p.systemAddress); break; case RakNetBindings.ID_USER_PACKET_ENUM: serverRakPeer.Send(inBitStream, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, p.systemAddress, false); break; } serverRakPeer.DeallocatePacket(p); } SystemAddress systemAddress = serverRakPeer.GetSystemAddressFromIndex(0); //if (systemAddress.binaryAddress != RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS.binaryAddress && // systemAddress.port != RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS.port) if(!systemAddress.Equals(RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS)) { RakNetStatistics rss = serverRakPeer.GetStatistics(systemAddress); if (RakNetBindings.GetTime() > lastLog + 4000) { Console.WriteLine("Packets sent:\t\t\t\t{0:D}", rss.packetsSent); lastLog = RakNetBindings.GetTime(); } } } else { foreach(Connection clientConnection in clientConnections) { Packet p = clientConnection.RakPeer.Receive(); if (p != null) { BitStream inBitStream = new BitStream(p, false); byte packetIdentifier; inBitStream.Read(out packetIdentifier); switch (packetIdentifier) { case RakNetBindings.ID_CONNECTION_REQUEST_ACCEPTED: Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED"); clientConnection.ConnectionCompleted = true; break; } clientConnection.RakPeer.DeallocatePacket(p); } if (clientConnection.ConnectionCompleted) { clientConnection.RakPeer.Send(dummyData, querySize, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, 0, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true); } } } Thread.Sleep(0); } //foreach (RakPeerInterface clientRakPeer in clientRakPeers) //{ // RakNetworkFactory.DestroyRakPeerInterface(clientRakPeer); //} //RakNetworkFactory.DestroyRakPeerInterface(serverRakPeer); }