/// <summary> /// Run example /// </summary> public static void RunExample() { //We need to define what happens when packets are received. //To do this we add an incoming packet handler for a 'Message' packet type. // //We will define what we want the handler to do inline by using a lambda expression //http://msdn.microsoft.com/en-us/library/bb397687.aspx. //We could also just point the AppendGlobalIncomingPacketHandler method //to a standard method (See AdvancedSend example) // //This handler will convert the incoming raw bytes into a string (this is what //the <string> bit means) and then write that string to the local console window. NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n ... Incoming message from " + connection.ToString() + " saying '" + incomingString + "'."); }); //Start listening for incoming 'TCP' connections. //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. //See also Connection.StartListening(ConnectionType.UDP, IPEndPoint) Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)); //Print the IP addresses and ports we are listening on to make sure everything //worked as expected. Console.WriteLine("Listening for TCP messages on:"); foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } //We loop here to allow any number of test messages to be sent and received while (true) { //Request a message to send somewhere Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):"); string stringToSend = Console.ReadLine(); //If the user has typed exit then we leave our loop and end the example if (stringToSend == "exit") { break; } else { //Once we have a message we need to know where to send it //We have created a small wrapper class to help keep things clean here ConnectionInfo targetServerConnectionInfo = ExampleHelper.GetServerDetails(); //There are loads of ways of sending data (see AdvancedSend example for more) //but the most simple, which we use here, just uses an IP address (string) and port (integer) //We pull these values out of the ConnectionInfo object we got above and voila! NetworkComms.SendObject("Message", ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Address.ToString(), ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Port, stringToSend); } } //We should always call shutdown on NetworkComms.Net if we have used it NetworkComms.Shutdown(); }
/// <summary> /// Run the AdvancedSend example. /// </summary> public static void RunExample() { Console.WriteLine("Unmanaged Connection Example ...\n"); //***************************************************************// // Start of interesting stuff // //***************************************************************// Console.WriteLine("\nNOTE: From this point on make sure both clients are configured in the same way if you want the example to work."); Console.WriteLine("\nIMPORTANT!! - Many of the features offered by NetworkComms.Net rely on managed connections, " + "i.e. those which enable the custom ApplicationLayerProtocol. If you use unmanaged connections, i.e. where the custom " + "application protocol has been disabled, you must take into account TCP packet fragmentation and concatenation, " + "correctly handling it, for all circumstances."); //Choose between unmanaged TCP or UDP SelectConnectionType(); //Add a packet handler for dealing with incoming unmanaged data NetworkComms.AppendGlobalIncomingUnmanagedPacketHandler((header, connection, array) => { Console.WriteLine("\nReceived unmanaged byte[] from " + connection.ToString()); for (int i = 0; i < array.Length; i++) { Console.WriteLine(i.ToString() + " - " + array[i].ToString()); } }); //Create suitable send receive options for use with unmanaged connections SendReceiveOptions optionsToUse = new SendReceiveOptions <NullSerializer>(); //Get the local IPEndPoints we intend to listen on //The port provided is '0' meaning select a random port. List <IPEndPoint> localIPEndPoints = (from current in HostInfo.IP.FilteredLocalAddresses() select new IPEndPoint(current, 0)).ToList(); //Create suitable listeners depending on the desired connectionType List <ConnectionListenerBase> listeners; if (connectionTypeToUse == ConnectionType.TCP) { //For each localIPEndPoint get a TCP listener //We need to set the ApplicationLayerProtocolStatus to Disabled listeners = (from current in localIPEndPoints select(ConnectionListenerBase) new TCPConnectionListener(optionsToUse, ApplicationLayerProtocolStatus.Disabled)).ToList(); } else { //We need to set the ApplicationLayerProtocolStatus to Disabled listeners = (from current in localIPEndPoints select(ConnectionListenerBase) new UDPConnectionListener(optionsToUse, ApplicationLayerProtocolStatus.Disabled, UDPConnection.DefaultUDPOptions)).ToList(); } //Start listening Connection.StartListening(listeners, localIPEndPoints, true); //***************************************************************// // End of interesting stuff // //***************************************************************// Console.WriteLine("Listening for incoming byte[] on:"); List <EndPoint> localListeningEndPoints = Connection.ExistingLocalListenEndPoints(connectionTypeToUse); foreach (IPEndPoint localEndPoint in localListeningEndPoints) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } Console.WriteLine("\nPress any key if you want to send data from this client. Press q to quit."); while (true) { //Wait for user to press something before sending anything from this end var keyContinue = Console.ReadKey(true); if (keyContinue.Key == ConsoleKey.Q) { break; } //Create the send object based on user input byteDataToSend = CreateSendArray(); //Get remote endpoint address //Expecting user to enter IP address as 192.168.0.1:4000 ConnectionInfo connectionInfo = ExampleHelper.GetServerDetails(ApplicationLayerProtocolStatus.Disabled); //***************************************************************// // Start of interesting stuff // //***************************************************************// Connection connectionToUse; //Create the connection if (connectionTypeToUse == ConnectionType.TCP) { connectionToUse = TCPConnection.GetConnection(connectionInfo, optionsToUse); } else { connectionToUse = UDPConnection.GetConnection(connectionInfo, UDPOptions.None, optionsToUse); } //Send the object connectionToUse.SendUnmanagedBytes(byteDataToSend); //***************************************************************// // End of interesting stuff // //***************************************************************// Console.WriteLine("\nSend complete. Press 'q' to quit or any other key to send something else."); } //***************************************************************// // Start of interesting stuff // //***************************************************************// //Make sure you call shutdown when finished to clean up. NetworkComms.Shutdown(); //***************************************************************// // End of interesting stuff // //***************************************************************// }
/// <summary> /// Run the AdvancedSend example. /// </summary> public static void RunExample() { Console.WriteLine("AdvancedSend Example ...\n"); //***************************************************************// // Start of interesting stuff // //***************************************************************// Console.WriteLine("\nNOTE: From this point on make sure both clients are configured in the same way if you want the example to work."); //Choose between TCP or UDP SelectConnectionType(); //Choose the serialiser and processors which network comms will use DataSerializer dataSerializer; SelectDataSerializer(out dataSerializer); List <DataProcessor> dataProcessors; Dictionary <string, string> dataProcessorOptions; //We cannot select data processors if the NullSerializer was selected if (dataSerializer.GetType() != typeof(NullSerializer)) { SelectDataProcessors(out dataProcessors, out dataProcessorOptions); } else { dataProcessors = new List <DataProcessor>(); dataProcessorOptions = new Dictionary <string, string>(); } NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions); //Add a packet handler for dealing with incoming connections. Function will be called when a packet is received with the specified type. We also here specify the type of object //we are expecting to receive. In this case we expect an int[] for packet type ArrayTestPacketInt NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>("ArrayByte", (header, connection, array) => { Console.WriteLine("\nReceived byte array from " + connection.ToString()); for (int i = 0; i < array.Length; i++) { Console.WriteLine(i.ToString() + " - " + array[i].ToString()); } }); //As above but this time we expect a string[], and use a different packet type to distinguish the difference NetworkComms.AppendGlobalIncomingPacketHandler <string[]>("ArrayString", (header, connection, array) => { Console.WriteLine("\nReceived string array from " + connection); for (int i = 0; i < array.Length; i++) { Console.WriteLine(i.ToString() + " - " + array[i]); } }); //Our custom object packet handler will be different depending on which serializer we have chosen if (NetworkComms.DefaultSendReceiveOptions.DataSerializer.GetType() == typeof(ProtobufSerializer)) { NetworkComms.AppendGlobalIncomingPacketHandler <ProtobufCustomObject>("CustomObject", (header, connection, customObject) => { Console.WriteLine("\nReceived custom protobuf object from " + connection); Console.WriteLine(" ... intValue={0}, stringValue={1}", customObject.IntValue, customObject.StringValue); }); } else if (NetworkComms.DefaultSendReceiveOptions.DataSerializer.GetType() == typeof(BinaryFormaterSerializer)) { NetworkComms.AppendGlobalIncomingPacketHandler <BinaryFormatterCustomObject>("CustomObject", (header, connection, customObject) => { Console.WriteLine("\nReceived custom binary formatter object from " + connection); Console.WriteLine(" ... intValue={0}, stringValue={1}", customObject.IntValue, customObject.StringValue); }); } else { NetworkComms.AppendGlobalIncomingPacketHandler <JSONSerializerCustomObject>("CustomObject", (header, connection, customObject) => { Console.WriteLine("\nReceived custom JSON object from " + connection); Console.WriteLine(" ... intValue={0}, stringValue={1}", customObject.IntValue, customObject.StringValue); }); } //Start listening for incoming connections //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. //If we wanted to listen on a specific port we would use that instead of '0' Connection.StartListening(connectionTypeToUse, new IPEndPoint(IPAddress.Any, 0)); //***************************************************************// // End of interesting stuff // //***************************************************************// Console.WriteLine("Listening for incoming objects on:"); List <EndPoint> localListeningEndPoints = Connection.ExistingLocalListenEndPoints(connectionTypeToUse); foreach (IPEndPoint localEndPoint in localListeningEndPoints) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } Console.WriteLine("\nPress any key if you want to send something from this client. Press q to quit."); while (true) { //Wait for user to press something before sending anything from this end var keyContinue = Console.ReadKey(true); if (keyContinue.Key == ConsoleKey.Q) { break; } //Create the send object based on user input CreateSendObject(); //Expecting user to enter IP address as 192.168.0.1:4000 ConnectionInfo connectionInfo = ExampleHelper.GetServerDetails(); //***************************************************************// // Start of interesting stuff // //***************************************************************// Connection connectionToUse; //Create the connection if (connectionTypeToUse == ConnectionType.TCP) { connectionToUse = TCPConnection.GetConnection(connectionInfo); } else { connectionToUse = UDPConnection.GetConnection(connectionInfo, UDPOptions.None); } //Send the object if (toSendType == typeof(Array)) { if (toSendObject.GetType().GetElementType() == typeof(byte)) { connectionToUse.SendObject("ArrayByte", toSendObject); } else { connectionToUse.SendObject("ArrayString", toSendObject); } } else { connectionToUse.SendObject("CustomObject", toSendObject); } //***************************************************************// // End of interesting stuff // //***************************************************************// Console.WriteLine("\nSend complete. Press 'q' to quit or any other key to send something else."); } //***************************************************************// // Start of interesting stuff // //***************************************************************// //Make sure you call shutdown when finished to clean up. NetworkComms.Shutdown(); //***************************************************************// // End of interesting stuff // //***************************************************************// }
/// <summary> /// Run example /// </summary> public static void RunExample() { //Select mode Console.WriteLine("SpeedTest Example ...\n"); Console.WriteLine("Please select host or peer mode:"); Console.WriteLine("1 - Host Mode (Catches Data)"); Console.WriteLine("2 - Peer Mode (Sends Data)"); //Read in user choice if (Console.ReadKey(true).Key == ConsoleKey.D1) { hostMode = true; } else { hostMode = false; } if (hostMode) { //Prepare DFS in host mode #region ServerMode Console.WriteLine("\n ... host mode selected."); NetworkComms.ConnectionEstablishShutdownDelegate clientEstablishDelegate = (connection) => { Console.WriteLine("Client " + connection.ConnectionInfo + " connected."); }; NetworkComms.ConnectionEstablishShutdownDelegate clientShutdownDelegate = (connection) => { Console.WriteLine("Client " + connection.ConnectionInfo + " disconnected."); }; NetworkComms.PacketHandlerCallBackDelegate <byte[]> IncomingDataDelegate = (packetHeader, connection, incomingObject) => { Console.WriteLine("Speed bytes received from " + connection.ConnectionInfo + "."); }; NetworkComms.AppendGlobalConnectionEstablishHandler(clientEstablishDelegate); NetworkComms.AppendGlobalConnectionCloseHandler(clientShutdownDelegate); NetworkComms.AppendGlobalIncomingPacketHandler("SpeedData", IncomingDataDelegate); //Start listening for TCP connections //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0)); Console.WriteLine("\nListening for incoming connections on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier); Console.WriteLine("\nPress 'q' to close host.\n"); while (true) { ConsoleKeyInfo pressedKey = Console.ReadKey(true); if (pressedKey.Modifiers != ConsoleModifiers.Control && pressedKey.Key == ConsoleKey.Q) { Console.WriteLine("Closing host."); break; } } #endregion } else if (!hostMode) { //Prepare DFS in peer mode #region PeerMode Console.WriteLine("\n ... peer mode selected."); Console.WriteLine("\nPlease enter how large the test data packet should be in MB and press return (larger is more accurate), e.g. 1024:"); int numberMegsToCreate = int.Parse(Console.ReadLine()); //Fill a byte[] with random data DateTime startTime = DateTime.Now; Random randGen = new Random(); byte[] someRandomData = new byte[numberMegsToCreate * 1024 * 1024]; randGen.NextBytes(someRandomData); Console.WriteLine("\nTest speed data created. Using {0}MB.\n", numberMegsToCreate); NetworkComms.PacketConfirmationTimeoutMS = 20000; ConnectionInfo serverConnectionInfo = ExampleHelper.GetServerDetails(); Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier); SendReceiveOptions nullCompressionSRO = new SendReceiveOptions <NullSerializer>(); //Add options which will require receive confirmations and also include packet construction time //in the packet header. nullCompressionSRO.Options.Add("ReceiveConfirmationRequired", ""); nullCompressionSRO.Options.Add("IncludePacketConstructionTime", ""); TCPConnection serverConnection = TCPConnection.GetConnection(serverConnectionInfo); Stopwatch timer = new Stopwatch(); while (true) { timer.Reset(); timer.Start(); serverConnection.SendObject("SpeedData", someRandomData, nullCompressionSRO); timer.Stop(); Console.WriteLine("SpeedData sent successfully with receive confirmation in {0}secs. Corresponds to {1}MB/s", (timer.ElapsedMilliseconds / 1000.0).ToString("0.00"), (numberMegsToCreate / (timer.ElapsedMilliseconds / 1000.0)).ToString("0.00")); } #endregion } NetworkComms.Shutdown(); }
/// <summary> /// Run example /// </summary> public static void RunExample() { Console.WriteLine("Secure Socket Layer (SSL) Example ...\n"); //Ensure we have a certificate to use //Maximum security is achieved by using a trusted certificate //To keep things simple here we just create a self signed certificate for testing string certName = "testCertificate.pfx"; if (!File.Exists(certName)) { Console.WriteLine("Creating self-signed test certificate - " + certName); CertificateDetails details = new CertificateDetails("CN=networkcomms.net", DateTime.Now, DateTime.Now.AddYears(1)); //We could increase/decrease the default key length if we want details.KeyLength = 1024; //Save the certificate to disk SSLTools.CreateSelfSignedCertificatePFX(details, certName); certificate = new X509Certificate2(certName); Console.WriteLine("\t... certificate successfully created."); } else { //Load an existing certificate Console.WriteLine("Loading existing certificate - " + certName); certificate = new X509Certificate2(certName); Console.WriteLine("\t... certificate successfully loaded."); } //Add a global incoming packet handler for packets of type "Message" //This handler will convert the incoming raw bytes into a string (this is what //the <string> bit means) and then write that string to the local console window. NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n ... Incoming message from " + connection.ToString() + " saying '" + incomingString + "'."); }); //Create suitable SSLOptions to use with TCP SelectSSLOptions(); //Get a list of all local endPoints using the default port List <IPEndPoint> desiredlocalEndPoints = (from current in HostInfo.IP.FilteredLocalAddresses() select new IPEndPoint(current, 0)).ToList(); //Create a list of matching TCP listeners where we provide the listenerSSLOptions List <ConnectionListenerBase> listeners = (from current in desiredlocalEndPoints select(ConnectionListenerBase)(new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, listenerSSLOptions))).ToList(); //Start listening for incoming TCP connections Connection.StartListening(listeners, desiredlocalEndPoints, true); //Print out the listening addresses and ports Console.WriteLine("\nListening for incoming TCP (SSL) connections on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } //We loop here to allow any number of test messages to be sent and received while (true) { //Request a message to send somewhere Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):"); string stringToSend = Console.ReadLine(); //If the user has typed exit then we leave our loop and end the example if (stringToSend == "exit") { break; } else { //Once we have a message we need to know where to send it //We have created a small wrapper class to help keep things clean here ConnectionInfo targetServerConnectionInfo = ExampleHelper.GetServerDetails(); try { //Get a connection to the target server using the connection SSL options we configured earlier //If there is a problem with the SSL handshake this will throw a CommsSetupShutdownException TCPConnection connection = TCPConnection.GetConnection(targetServerConnectionInfo, sendingSendReceiveOptions, connectionSSLOptions); //Send our message of the encrypted connection connection.SendObject("Message", stringToSend); } catch (CommsException) { //We catch all exceptions by using CommsException Console.WriteLine("\nERROR - Connection to " + targetServerConnectionInfo + " was unsuccessful." + " Server is either not listening or the entered SSL configurations" + "are not compatible. Please check settings and try again."); } } } //If we have used comms features we must gracefully shutdown NetworkComms.Shutdown(); }
/// <summary> /// Run the example /// </summary> public void Run() { //Expecting user to enter ip address as 192.168.0.1:4000 ConnectionInfo connectionInfo = ExampleHelper.GetServerDetails(); SelectConnectionType(); try { //We would really like to create a local instance of MathClass, but the client does not have a //reference to MathClass (defined server side only): // //IMath remoteObject = new MathClass(); // //This example is all about RPC, so we create the instance remotely instead, as follows ... //We need to select our remote object using one of the available access methods string instanceId = ""; Connection connection = null; if (connectionTypeToUse == ConnectionType.TCP) { connection = TCPConnection.GetConnection(connectionInfo); } else { connection = UDPConnection.GetConnection(connectionInfo, UDPOptions.None); } //Get the remote object IMath remoteObject = SelectRemoteObject(connection, out instanceId); //Add a handler to the object's event to demonstrate remote triggering of events remoteObject.EchoEvent += (sender, args) => { Console.WriteLine("Echo event received saying {0}", args.EchoValue); }; Console.WriteLine("\nRemote object has been selected. RPC object instanceId: {0}", instanceId); while (true) { //We can now perform RPC operations on our remote object Console.WriteLine("\nPlease press 'y' key to perform some remote math. Any other key will quit the example."); string message = Console.ReadKey(true).KeyChar.ToString().ToLower(); //If the user has typed exit then we leave our loop and end the example if (message == "y") { //We pass our remoteObject to our local method DoMath to keep this area of code clean Console.WriteLine("Result: " + DoMath(remoteObject).ToString()); } else { break; } } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { NetworkComms.Shutdown(); } }
/// <summary> /// Run example /// </summary> public static void RunExample() { Console.WriteLine("IntermediateSend Example ...\n"); //Set the default send receive options to use for all communication // //Serializers convert custom objects into byte[] which is required for transmission // - Here we have selected the ProtobufSerializer. For more please see the AdvancedSend example. // //Data processors manipulate the raw byte[] of an object, some encrypt, some compress etc etc. // - Here we have selected a single data processor which will compress data, the LZMACompressor // For more please see the AdvancedSend example. NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions <ProtobufSerializer, LZMACompressor>(); //Ensure the packet construction time is included in all sent packets NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true; //Ensure all incoming packets are handled with the priority AboveNormal NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority = QueueItemPriority.AboveNormal; //We need to define what happens when packets are received. //To do this we add an incoming packet handler for a 'Message' packet type. //You are free to choose your own packet types. // //This handler will expect the incoming raw bytes to be converted to a string (this is what the <string> bit means). NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", HandleIncomingMessagePacket); //Start listening for incoming 'TCP' connections. //We want to select a random port on all available adaptors so provide //an IPEndPoint using IPAddress.Any and port 0. //See also Connection.StartListening(ConnectionType.UDP, IPEndPoint) Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0)); //Print the IP addresses and ports we are listening on to make sure everything //worked as expected. Console.WriteLine("Listening for TCP messages on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } //We loop here to allow any number of test messages to be sent and received while (true) { //Request a message to send somewhere Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):"); string stringToSend = Console.ReadLine(); //If the user has typed exit then we leave our loop and end the example if (stringToSend == "exit") { break; } else { try { //Once we have a message we need to know where to send it //We have created a small wrapper class to help keep things clean here ConnectionInfo targetServerConnectionInfo = ExampleHelper.GetServerDetails(); //We get a connection to the desired target server //This is performed using a static method, i.e. 'TCPConnection.GetConnection()' instead of //using 'new TCPConnection()' to ensure thread safety. This means if you have a multi threaded application //and attempt to get a connection the same target server simultaneously, you will only ever create //a single connection. Connection conn = TCPConnection.GetConnection(targetServerConnectionInfo); //We send the string using a 'Message' packet type //There are a large number of overrides to SendObject //Please see our other examples or the online API //http://www.networkcomms.net/api/ conn.SendObject("Message", stringToSend); } catch (CommsException ex) { //All NetworkComms.Net exception inherit from CommsException so we can easily //catch all just by catching CommsException. For the break down of exceptions please //see our online API. //http://www.networkcomms.net/api/ //If an error occurs we need to decide what to do. //In this example we will just log to a file and continue. LogTools.LogException(ex, "IntermediateSendExampleError", "rekt m9"); Console.WriteLine("\nError: CommsException was caught. Please see the log file created for more information.\n"); } } } //We should always call shutdown on NetworkComms.Net if we have used it NetworkComms.Shutdown(); }
/// <summary> /// The distributed file system (DFS) allows for the high performance distribution of large files /// within a cluster of peers. This sytem replicates the behaviour the bitTorrent protocol by using /// NetworkCommsDotNet. This example demonstrates the DFS in action. /// </summary> public static void RunExample() { //Select mode Console.WriteLine("Distributed File System (DFS) Example ...\n"); Console.WriteLine("Please select host or peer mode:"); Console.WriteLine("1 - Host Mode (Original source of data)"); Console.WriteLine("2 - Peer Mode (Builds data and then acts as subhost)"); //Read in user choice if (Console.ReadKey(true).Key == ConsoleKey.D1) { hostMode = true; } else { hostMode = false; } if (hostMode) { //Prepare DFS in host mode #region ServerMode Console.WriteLine("\n ... host mode selected."); Console.WriteLine("\nPlease enter how large the test data packet should be in MB and press return, e.g. 50:"); int numberMegsToCreate = int.Parse(Console.ReadLine()); //Fill a byte[] with random data DateTime startTime = DateTime.Now; Random randGen = new Random(); byte[] someRandomData = new byte[numberMegsToCreate * 1024 * 1024]; randGen.NextBytes(someRandomData); Console.WriteLine("\n ... successfully created a {0}MB test packet.", ((double)someRandomData.Length / (1024.0 * 1024.0)).ToString("0.###")); object listLocker = new object(); List <IPEndPoint> connectedClients = new List <IPEndPoint>(); //Initialise the DFS before creating the test object to ensure the correct port and IP are used as the seed DFS.Initialise(10000); //Create the item to be distributed List <ConnectionInfo> seedConnectionInfoList = (from current in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP) select new ConnectionInfo(ConnectionType.TCP, NetworkComms.NetworkIdentifier, current, true)).ToList(); DistributedItem newItem = new DistributedItem("exampleItem", "exampleItem", new MemoryStream(someRandomData), seedConnectionInfoList, DataBuildMode.Disk_Single); NetworkComms.ConnectionEstablishShutdownDelegate clientEstablishDelegate = (connection) => { lock (listLocker) connectedClients.Remove((IPEndPoint)connection.ConnectionInfo.RemoteEndPoint); Console.WriteLine("Client " + connection.ConnectionInfo + " connected."); }; NetworkComms.ConnectionEstablishShutdownDelegate clientShutdownDelegate = (connection) => { lock (listLocker) connectedClients.Remove((IPEndPoint)connection.ConnectionInfo.RemoteEndPoint); Console.WriteLine("Client " + connection.ConnectionInfo + " disconnected."); }; NetworkComms.PacketHandlerCallBackDelegate <int> ReplyDelegate = (packetHeader, connection, incomingObject) => { //Push the item into the swarm lock (listLocker) if (!connectedClients.Contains(connection.ConnectionInfo.RemoteEndPoint)) { connectedClients.Add((IPEndPoint)connection.ConnectionInfo.RemoteEndPoint); } DFS.PushItemToPeer(connection, newItem, "BigDataRequestResponse"); Console.WriteLine("Pushing item to " + connection.ConnectionInfo + " (" + connection.ConnectionInfo.NetworkIdentifier + "). {0} in swarm. P#={1}, S#={2}.", connectedClients.Count, newItem.PushCount, newItem.TotalChunkSupplyCount); }; NetworkComms.PacketHandlerCallBackDelegate <string> InfoDelegate = (packetHeader, connectionId, incomingString) => { Console.WriteLine(" ... " + connectionId + " - " + incomingString); }; Console.WriteLine(" ... DFS has been initialised."); NetworkComms.AppendGlobalConnectionEstablishHandler(clientEstablishDelegate); NetworkComms.AppendGlobalConnectionCloseHandler(clientShutdownDelegate); NetworkComms.AppendGlobalIncomingPacketHandler("BigDataRequest", ReplyDelegate); NetworkComms.AppendGlobalIncomingPacketHandler("ClientInfo", InfoDelegate); Console.WriteLine("\nListening for incoming connections on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier); Console.WriteLine("\nPress 's' to write out stats, 'q' to close any connected peers, 'ctrl+q' to close this host.\n"); while (true) { ConsoleKeyInfo pressedKey = Console.ReadKey(true); #region Host Shutdown if (pressedKey.Modifiers != ConsoleModifiers.Control && pressedKey.Key == ConsoleKey.Q) { Console.WriteLine("Sending shutdown to clients..."); lock (listLocker) { for (int i = 0; i < connectedClients.Count; i++) { try { TCPConnection.GetConnection(new ConnectionInfo(connectedClients[i])).SendObject("ClientCommand", 0); } catch (Exception) { Console.WriteLine("Exception telling client to shutdown. Probably already disconnected."); } } } } else if (pressedKey.Modifiers == ConsoleModifiers.Control && pressedKey.Key == ConsoleKey.Q) { Console.WriteLine("Sending shutdown to clients and closing local host..."); lock (listLocker) { for (int i = 0; i < connectedClients.Count; i++) { try { TCPConnection.GetConnection(new ConnectionInfo(connectedClients[i])).SendObject("ClientCommand", 0); } catch (Exception) { Console.WriteLine("Exception telling client to shutdown. Probably already disconnected."); } } } Console.WriteLine("Closing host."); break; } else if (pressedKey.Key == ConsoleKey.S) { #region Stats Console.WriteLine("\nCurrent Stats:"); Console.WriteLine("{0} comms connections.", NetworkComms.TotalNumConnections()); if (NetworkComms.TotalNumConnections() > 0) { Console.WriteLine("Connections with: "); var connections = NetworkComms.GetExistingConnection(); foreach (var connection in connections) { Console.WriteLine("\t{0}", connection.ConnectionInfo); } } #endregion } #endregion } #endregion } else if (!hostMode) { //Prepare DFS in peer mode #region PeerMode Console.WriteLine("\n ... peer mode selected."); ConnectionInfo serverConnectionInfo = ExampleHelper.GetServerDetails(); DFS.Initialise(10000); Console.WriteLine(" ... DFS has been initialised."); bool shutDown = false; bool buildComplete = true; DateTime startTime = DateTime.Now; int buildCount = 0; NetworkComms.PacketHandlerCallBackDelegate <byte[]> ReplyDelegate = (packetHeader, connection, dataBytes) => { try { buildCount++; DistributedItem item = DFS.MostRecentlyCompletedItem(); Console.WriteLine(" ... full item build " + buildCount + " took {0} secs ({1} MB/s) using {2} total peers. {3} builds completed.", (DateTime.Now - startTime).TotalSeconds.ToString("0.00"), (((double)dataBytes.Length / 1048576.0) / (DateTime.Now - startTime).TotalSeconds).ToString("0.0"), item.SwarmChunkAvailability.NumPeersInSwarm(), buildCount); double speed = (((double)dataBytes.Length / 1048576.0) / (DateTime.Now - startTime).TotalSeconds); connection.SendObject("ClientInfo", " ... build " + buildCount + " took " + (DateTime.Now - startTime).TotalSeconds.ToString("0.00") + " secs (" + speed.ToString("0.0") + " MB/s) using " + item.SwarmChunkAvailability.NumPeersInSwarm() + " peers. " + buildCount + " builds completed."); buildComplete = true; } catch (Exception) { Console.WriteLine("Shutting down due to exception."); shutDown = true; } }; NetworkComms.PacketHandlerCallBackDelegate <int> ShutdownDelegate = (packetHeader, connectionId, packetDataBytes) => { shutDown = true; }; NetworkComms.AppendGlobalIncomingPacketHandler("BigDataRequestResponse", ReplyDelegate); NetworkComms.AppendGlobalIncomingPacketHandler("ClientCommand", ShutdownDelegate); Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier); Console.WriteLine("\nListening for incoming objects on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } startTime = DateTime.Now; while (true) { if (!shutDown && buildComplete) { Console.WriteLine("\nPress 'r' to rebuild or any other key to shutdown."); var shutdownKey = Console.ReadKey(true).Key; if (shutdownKey != ConsoleKey.R) { shutDown = true; } if (!shutDown) { DistributedItem item = DFS.MostRecentlyCompletedItem(); if (item != null) { DFS.RemoveItem(item.Data.CompleteDataCheckSum); Console.WriteLine("\n ... item removed from local and rebuilding at {0}.", DateTime.Now.ToString("HH:mm:ss.fff")); startTime = DateTime.Now; } buildComplete = false; TCPConnection.GetConnection(serverConnectionInfo).SendObject("BigDataRequest"); Console.WriteLine(" ... initiating item build ..."); } } else if (shutDown) { shutDown = true; DFS.Shutdown(); break; } Thread.Sleep(250); } try { TCPConnection.GetConnection(serverConnectionInfo).SendObject("ClientInfo", "... shutting down, initiating DFS shutdown."); } catch (CommsException) { Console.WriteLine("... unable to inform local of shutdown. Connection probably already closed."); } Console.WriteLine("Done. Completed {0} builds.", buildCount); #endregion } DFS.Shutdown(); NetworkComms.Shutdown(); }