示例#1
0
 public void Stop()
 {
     if (listener != null)
     {
         listener.Dispose();
     }
     listener = null;
 }
示例#2
0
        private static void StartListening(string ipAdress, int port)
        {
            SendReceiveOptions optionsToUse = new SendReceiveOptions <NullSerializer>();
            IPEndPoint         iPEndPoint   = new IPEndPoint(IPAddress.Parse(ipAdress), port);
            var listener = new TCPConnectionListener(optionsToUse, ApplicationLayerProtocolStatus.Disabled);

            Connection.StartListening(listener, iPEndPoint);
            Console.WriteLine("Started Listening from IP:" + iPEndPoint.Address + " on Port:" + iPEndPoint.Port);
        }
示例#3
0
 /// <summary>
 /// Start the TCP listener
 /// </summary>
 public static void Listen()
 {
     if (Net.ENABLE_DISCOVERY)
     {
         Net.ConfigurePeerDiscovery();
         PeerDiscovery.EnableDiscoverable(Net.PEER_DISCOVERY_METHOD);
     }
     NetworkComms.EnableLogging(new LiteLoggerDebug(LiteLoggerDebug.LogMode.ConsoleOnly));
     Connection.StartListening(Listener = new TCPConnectionListener(Net.SEND_RECEIVE_OPTIONS, ApplicationLayerProtocolStatus.Enabled, true), new IPEndPoint(IPAddress.Any, Net.DEFAULT_PORT));
 }
示例#4
0
        public void Start()
        {
            listener = new TCPConnectionListener(tcpPort);
            listener.ClientConnected += listener_ClientConnected;
            listener.Listening        = true;

            udpConnection = new UDPConnection();
            udpConnection.PacketRecievedAsync +=
                new BaseConnection.PacketRecievedAsyncEventHandler(udpConnection_PacketRecievedAsync);
            udpConnection.Bind(new IPEndPoint(IPAddress.Any, udpPort));
            udpConnection.Receiving = true;
        }
示例#5
0
        private void StartListening(string ipAdress, int port)
        {
            SendReceiveOptions optionsToUse = new SendReceiveOptions <NullSerializer>();
            IPEndPoint         iPEndPoint   = new IPEndPoint(IPAddress.Parse(ipAdress), port);

            listener = new TCPConnectionListener(optionsToUse, ApplicationLayerProtocolStatus.Disabled);
            listener.AppendIncomingUnmanagedPacketHandler((header, connection, array) =>
            {
                PacketParser.ParseUnmanagedPacket(array, connection);
            });
            Connection.StartListening(listener, iPEndPoint);
            Console.WriteLine("Started Listening from IP:" + iPEndPoint.Address + " on Port:" + iPEndPoint.Port);
        }
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            //NetworkComms.PacketConfirmationTimeoutMS = 1000000;

            //var processors = new List<DataProcessor> { DPSManager.GetDataProcessor<SharpZipLibCompressor.SharpZipLibGzipCompressor>(), DPSManager.GetDataProcessor<RijndaelPSKEncrypter>() };
            var processors = new List <DataProcessor> {
                DPSManager.GetDataProcessor <RijndaelPSKEncrypter>()
            };
            var dataOptions = new Dictionary <string, string>();

            RijndaelPSKEncrypter.AddPasswordToOptions(dataOptions, "oj1N0bcfsjtQxfgRKT7B");
            var options = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), processors, dataOptions)
            {
                UseNestedPacket = false
            };

            //Uncomment to make it work
            //RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "oj1N0bcfsjtQxfgRKT7B");

            var points   = new List <IPEndPoint>();
            var localIPs = HostInfo.IP.FilteredLocalAddresses();

            foreach (var ip in localIPs)
            {
                var listener = new TCPConnectionListener(options, ApplicationLayerProtocolStatus.Enabled);
                listener.AppendIncomingPacketHandler <string>("Kill all humans",
                                                              (header, con, customObject) =>
                {
                    Console.WriteLine("\nReceived custom protobuf object from " + con);
                }, options);
                Connection.StartListening(listener, new IPEndPoint(ip, 0));
                points.Add(listener.LocalListenEndPoint as IPEndPoint);
            }

            Console.WriteLine("Listening on:");
            foreach (var endpoint in points)
            {
                Console.WriteLine("{0}:{1}", endpoint.Address.ToString(), endpoint.Port.ToString());
            }

            var point = points.First();
            //IPEndPoint point = IPTools.ParseEndPointFromString("::1:46112");

            var connectionInfo = new ConnectionInfo(point);
            var connection     = TCPConnection.GetConnection(connectionInfo);

            options.ReceiveConfirmationRequired = true;
            connection.SendObject("Kill all humans", "Bite my shiny metal ass", options);

            Console.ReadLine();
        }
示例#7
0
        string[] Blocks;                         //сами блоки в двоичном формате

        void Main(string[] args)
        {
            // listen for incoming connection
            var listener = new TCPConnectionListener(IPAddress.Any, 8080);

            listener._incomingConnection += OnIncomingConnection;
            listener.Start();
            Console.WriteLine("Server started. Press Enter to exit.\n");

            // wait for 'Enter' to stop listener
            ConsoleKeyInfo keyInfo = Console.ReadKey();

            while (keyInfo.Key != ConsoleKey.Enter)
            {
                keyInfo = Console.ReadKey();
            }

            listener.Stop();
        }
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            //NetworkComms.PacketConfirmationTimeoutMS = 1000000;

            //var processors = new List<DataProcessor> { DPSManager.GetDataProcessor<SharpZipLibCompressor.SharpZipLibGzipCompressor>(), DPSManager.GetDataProcessor<RijndaelPSKEncrypter>() };
            var processors = new List<DataProcessor> { DPSManager.GetDataProcessor<RijndaelPSKEncrypter>() };
            var dataOptions = new Dictionary<string, string>();
            RijndaelPSKEncrypter.AddPasswordToOptions(dataOptions, "oj1N0bcfsjtQxfgRKT7B");
            var options = new SendReceiveOptions(DPSManager.GetDataSerializer<ProtobufSerializer>(), processors, dataOptions) { UseNestedPacket = false };

            //Uncomment to make it work
            //RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "oj1N0bcfsjtQxfgRKT7B");

            var points = new List<IPEndPoint>();
            var localIPs = HostInfo.IP.FilteredLocalAddresses();
            foreach (var ip in localIPs)
            {
                var listener = new TCPConnectionListener(options, ApplicationLayerProtocolStatus.Enabled);
                listener.AppendIncomingPacketHandler<string>("Kill all humans",
                                (header, con, customObject) =>
                                {
                                    Console.WriteLine("\nReceived custom protobuf object from " + con);
                                }, options);
                Connection.StartListening(listener, new IPEndPoint(ip, 0));
                points.Add(listener.LocalListenEndPoint as IPEndPoint);
            }

            Console.WriteLine("Listening on:");
            foreach (var endpoint in points)
                Console.WriteLine("{0}:{1}", endpoint.Address.ToString(), endpoint.Port.ToString());

            var point = points.First();
            //IPEndPoint point = IPTools.ParseEndPointFromString("::1:46112");

            var connectionInfo = new ConnectionInfo(point);
            var connection = TCPConnection.GetConnection(connectionInfo);

            options.ReceiveConfirmationRequired = true;
            connection.SendObject("Kill all humans", "Bite my shiny metal ass", options);

            Console.ReadLine();
        }
        public static void StartListening(IPEndPoint newLocalEndPoint, bool useRandomPortFailOver = true, bool allowDiscoverable = false)
        {
            if (newLocalEndPoint.Address == IPAddress.Any)
                throw new NotSupportedException("IPAddress.Any may not be specified for this depreciated method. Please use Connection.StartListening() instead.");

            TCPConnectionListener listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, allowDiscoverable);
            Connection.StartListening(listener, newLocalEndPoint, useRandomPortFailOver);
        }
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = 600000;

            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.PacketHandlerCallBackDelegate<byte[]> callback = (header, connection, data) =>
                {
                    if (data == null)
                        Console.WriteLine("Received null array from " + connection.ToString());
                    else
                        Console.WriteLine("Received data (" + data + ") from " + connection.ToString());
                };

                //NetworkComms.AppendGlobalIncomingPacketHandler("Data", callback);

                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
                RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "somePassword!!");

                ConnectionListenerBase listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled);
                listener.AppendIncomingPacketHandler("Data", callback);

                Connection.StartListening(listener, new IPEndPoint(localIPAddress, 10000), true);

                Console.WriteLine("\nListening for UDP messages on:");
                foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP)) 
                   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));

                SendReceiveOptions customOptions = (SendReceiveOptions)NetworkComms.DefaultSendReceiveOptions.Clone();
                
                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
                //RijndaelPSKEncrypter.AddPasswordToOptions(customOptions.Options, "somePassword!!");

                customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<SharpZipLibCompressor.SharpZipLibGzipCompressor>());

                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<DataPadder>());
                //DataPadder.AddPaddingOptions(customOptions.Options, 10240, DataPadder.DataPaddingType.Random, false);

                //customOptions.UseNestedPacket = true;

                Connection conn = TCPConnection.GetConnection(serverInfo, customOptions);

                sendArray = null;
                conn.SendObject("Data", sendArray);

                Console.WriteLine("Sent data to server.");

                Console.WriteLine("\nClient complete. Press any key to quit.");
                Console.ReadKey(true);
            }
        }
示例#11
0
        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();
        }
示例#12
0
        public void TestTCPConnect()
        {
            bool           success  = false;
            AutoResetEvent testDone = new AutoResetEvent(false);

            TCPConnectionListener listener = new TCPConnectionListener(5013);

            listener.Listening = true;
            TCPConnection client1 = null;

            listener.ClientConnected +=
                delegate(object sender, TCPConnectionListener.ClientConnectedEventArgs e)
            {
                Console.WriteLine("Client connected to server!");
                TCPConnection serverClient1 = new TCPConnection(e.CL);
                serverClient1.SendPacket(new byte[] { 1, 2, 3, 4 }, TCPPacketBuilder.TCPPacketFlags.None);
                serverClient1.Receiving = true;


                serverClient1.PacketRecievedAsync +=
                    delegate(object sender2, BaseConnection.PacketRecievedEventArgs e2)
                {
                    for (int i = 1; i < 4 + 1; i++)
                    {
                        if (e2.Dgram[i - 1] != i)
                        {
                            success = false;         // optional
                            testDone.Set();
                            return;
                        }
                    }
                    Console.WriteLine("Packet received from client!");

                    success = true;
                    testDone.Set();
                };
            };


            client1 = new TCPConnection();

            client1.ConnectedToServer +=
                delegate(object sender, TCPConnection.ConnectedToServerEventArgs e)
            {
                Console.WriteLine("Connected successfully!");
                client1.Receiving = true;
            };

            client1.ConnectError +=
                delegate(object sender, TCPConnection.ConnectErrorEventArgs e)
            {
                throw e.Ex;
            };

            client1.PacketRecievedAsync +=
                delegate(object sender, BaseConnection.PacketRecievedEventArgs e)
            {
                for (int i = 1; i < 4 + 1; i++)
                {
                    if (e.Dgram[i - 1] != i)
                    {
                        success = false;     // optional
                        testDone.Set();
                        return;
                    }
                }
                Console.WriteLine("Packet received from server!");
                client1.SendPacket(new byte[] { 1, 2, 3, 4 }, TCPPacketBuilder.TCPPacketFlags.None);
            };



            client1.Connect(System.Net.IPAddress.Parse("127.0.0.1"), 5013);

            //testDone.WaitOne(5000);
            testDone.WaitOne();

            Assert.True(success);
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod">The discovery method for which this peer should be discoverable</param>
        /// <param name="localDiscoveryEndPoint">The local endpoint with which to make this peer discoverable</param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod, EndPoint localDiscoveryEndPoint)
        {
#if !NETFX_CORE && !WINDOWS_PHONE
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
            {
                lock (_syncRoot)
                {
                    if (_discoveryListeners.ContainsKey(discoveryMethod))
                        return;

                    if (!HostInfo.IP.FilteredLocalAddresses().Contains((localDiscoveryEndPoint as IPEndPoint).Address))
                        throw new ArgumentException("Provided endpoint must use a valid local address", "localDiscoveryEndPoint");

                    if ((localDiscoveryEndPoint as IPEndPoint).Port == 0)
                    {
                        IPAddress address = (localDiscoveryEndPoint as IPEndPoint).Address;

                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }
                    else
                    {
                        //Based on the connection type select all local endPoints and then enable discoverable
                        ConnectionListenerBase listener;
                        if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                            listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                        else
                            listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                        Connection.StartListening(listener, localDiscoveryEndPoint);

                        //Once we are successfully listening we can break
                        _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                    }

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#if NET35 || NET4
            else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
            {
                lock (_syncRoot)
                {
                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                        if (radio.LocalAddress == (localDiscoveryEndPoint as BluetoothEndPoint).Address)
                            radio.Mode = RadioMode.Discoverable;

                    _discoveryListeners.Add(discoveryMethod, Connection.StartListening(ConnectionType.Bluetooth, localDiscoveryEndPoint, true));

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#endif
            else
                throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// Uses all suitable and allowed adaptors, e.g. for IP networks uses <see cref="HostInfo.IP.FilteredLocalAddresses()"/>.
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod"></param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod)
        {
            lock (_syncRoot)
            {
                if (_discoveryListeners.ContainsKey(discoveryMethod))
                    return;

                //Based on the connection type select all local endPoints and then enable discoverable
#if !NETFX_CORE && !WINDOWS_PHONE
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
                {
                    //We should select one of the target points across all adaptors, no need for all adaptors to have
                    //selected a single uniform port which is what happens if we just pass IPAddress.Any to the StartListening method
                    List<IPAddress> localAddresses = new List<IPAddress>();

                    if (ListenMode == LocalListenMode.EachAdaptorIndependently || ListenMode == LocalListenMode.Both)
                        localAddresses.AddRange(HostInfo.IP.FilteredLocalAddresses());

                    if (ListenMode == LocalListenMode.OnlyZeroAdaptor || ListenMode == LocalListenMode.Both)
                        localAddresses.Add(IPAddress.Any);

                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();
                    foreach (IPAddress address in localAddresses)
                    {
                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                listeners.Add(listener);
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }

                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#if NET35 || NET4
                else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
                {
                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();

                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                    {
                        radio.Mode = RadioMode.Discoverable;
                        listeners.AddRange(Connection.StartListening(ConnectionType.Bluetooth, new BluetoothEndPoint(radio.LocalAddress, BluetoothDiscoveryService), true));
                    }
                    
                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#endif
                else
                    throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
                
                //Add the packet handlers if required
                foreach (var byMethodPair in _discoveryListeners)
                {
                    foreach(ConnectionListenerBase listener in byMethodPair.Value)
                    {
                        if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                            listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                    }
                }
                    
            }
        }
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = 600000;

            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.PacketHandlerCallBackDelegate <byte[]> callback = (header, connection, data) =>
                {
                    if (data == null)
                    {
                        Console.WriteLine("Received null array from " + connection.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Received data (" + data + ") from " + connection.ToString());
                    }
                };

                //NetworkComms.AppendGlobalIncomingPacketHandler("Data", callback);

                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
                RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "somePassword!!");

                ConnectionListenerBase listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled);
                listener.AppendIncomingPacketHandler("Data", callback);

                Connection.StartListening(listener, new IPEndPoint(localIPAddress, 10000), true);

                Console.WriteLine("\nListening for UDP messages on:");
                foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP))
                {
                    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));

                SendReceiveOptions customOptions = (SendReceiveOptions)NetworkComms.DefaultSendReceiveOptions.Clone();

                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
                //RijndaelPSKEncrypter.AddPasswordToOptions(customOptions.Options, "somePassword!!");

                customOptions.DataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());

                //customOptions.DataProcessors.Add(DPSManager.GetDataProcessor<DataPadder>());
                //DataPadder.AddPaddingOptions(customOptions.Options, 10240, DataPadder.DataPaddingType.Random, false);

                //customOptions.UseNestedPacket = true;

                Connection conn = TCPConnection.GetConnection(serverInfo, customOptions);

                sendArray = null;
                conn.SendObject("Data", sendArray);

                Console.WriteLine("Sent data to server.");

                Console.WriteLine("\nClient complete. Press any key to quit.");
                Console.ReadKey(true);
            }
        }
示例#16
0
        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();
        }