/// <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(); }
public static void RunExample() { NetworkComms.ConnectionEstablishTimeoutMS = 600000; //Create a suitable certificate if it does not exist if (!File.Exists("testCertificate.pfx")) { CertificateDetails details = new CertificateDetails("CN=networkcomms.net", DateTime.Now, DateTime.Now.AddYears(1)); SSLTools.CreateSelfSignedCertificatePFX(details, "testCertificate.pfx"); } //Load the certificate X509Certificate cert = new X509Certificate2("testCertificate.pfx"); IPAddress localIPAddress = IPAddress.Parse("::1"); Console.WriteLine("Please select mode:"); Console.WriteLine("1 - Server (Listens for connections)"); Console.WriteLine("2 - Client (Creates connections to server)"); //Read in user choice if (Console.ReadKey(true).Key == ConsoleKey.D1) { serverMode = true; } else { serverMode = false; } if (serverMode) { NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>("Data", (header, connection, data) => { Console.WriteLine("Received data (" + data.Length + ") from " + connection.ToString()); }); //Establish handler NetworkComms.AppendGlobalConnectionEstablishHandler((connection) => { Console.WriteLine("Connection established - " + connection); }); //Close handler NetworkComms.AppendGlobalConnectionCloseHandler((connection) => { Console.WriteLine("Connection closed - " + connection); }); SSLOptions sslOptions = new SSLOptions(cert, true, true); TCPConnectionListener listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, sslOptions); Connection.StartListening(listener, new IPEndPoint(localIPAddress, 10000), true); Console.WriteLine("\nListening for TCP (SSL) messages on:"); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port); } Console.WriteLine("\nPress any key to quit."); ConsoleKeyInfo key = Console.ReadKey(true); } else { ConnectionInfo serverInfo = new ConnectionInfo(new IPEndPoint(localIPAddress, 10000)); SSLOptions sslOptions = new SSLOptions("networkcomms.net", true); //SSLOptions sslOptions = new SSLOptions(cert, true); TCPConnection conn = TCPConnection.GetConnection(serverInfo, NetworkComms.DefaultSendReceiveOptions, sslOptions); conn.SendObject("Data", sendArray); Console.WriteLine("Sent data to server."); Console.WriteLine("\nClient complete. Press any key to quit."); Console.ReadKey(true); } NetworkComms.Shutdown(); }