Ejemplo n.º 1
0
        private Client()
        {
            NetworkComms.DisableLogging();

            NetworkComms.IgnoreUnknownPacketTypes = true;
            var serializer = DPSManager.GetDataSerializer <ProtobufSerializer>();

            NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(
                DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(serializer,
                                                                            NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);

            RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, Utility.PSK);

            NetworkComms.AppendGlobalIncomingPacketHandler <Ping>(Ping.Header, PingHandler);
            NetworkComms.AppendGlobalIncomingPacketHandler <ClassInfo>(ClassInfo.Header, ClassInfoHandler);
            NetworkComms.AppendGlobalIncomingPacketHandler <InstructorLogin>(InstructorLogin.Header, InstructorLoginHandler);
            NetworkComms.AppendGlobalIncomingPacketHandler <ClientInfo>(ClientInfo.Header, ClientInfoHandler);
            PeerDiscovery.EnableDiscoverable(PeerDiscovery.DiscoveryMethod.UDPBroadcast);

            PeerDiscovery.OnPeerDiscovered += OnPeerDiscovered;

            //NetworkComms.AppendGlobalIncomingPacketHandler<byte[]>("PartialFileData", IncomingPartialFileData);

            //NetworkComms.AppendGlobalIncomingPacketHandler<SendInfo>("PartialFileDataInfo",
            //    IncomingPartialFileDataInfo);

            //NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClose);

            PeerDiscovery.DiscoverPeersAsync(PeerDiscovery.DiscoveryMethod.UDPBroadcast);
        }
Ejemplo n.º 2
0
        public Server()
        {
            users = new Dictionary <Connection, ConnectedUser>();

            authentication        = new PacketHandling.Authentication(this);
            addNewContact         = new PacketHandling.AddNewContact(this);
            addNewContactResponse = new PacketHandling.AddNewContactResponse(this);
            personalUserUpdate    = new PacketHandling.PersonalUserUpdate(this);
            deleteAndBlockContact = new PacketHandling.DeleteAndBlockContact(this);
            transferMessage       = new PacketHandling.TransferMessage(this);
            transferNudge         = new PacketHandling.TransferNudge(this);
            transferWritingStatus = new PacketHandling.TransferWritingStatus(this);

            accountManager = new AccountManager();

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);
            if (!NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>()))
            {
                RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, Config.Properties.SERVER_ENCRYPTION_KEY);
                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
            }

            NetworkComms.Shutdown();
            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, Config.Properties.SERVER_PORT));

            foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Program.WriteToConsole("Local End Point: " + listenEndPoint.Address + ":" + listenEndPoint.Port);
            }

            BroadCastContacts(Config.Properties.BROADCAST_INTERVAL);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Toggle encryption
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void UseEncryptionBox_CheckedToggle(object sender, RoutedEventArgs e)
 {
     if (useEncryptionBox.IsChecked != null && (bool)useEncryptionBox.IsChecked)
     {
         RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, encryptionKey);
         NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
     }
     else
     {
         NetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
     }
 }
        /// <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();
        }
Ejemplo n.º 5
0
        private Server()
        {
            var serializer = DPSManager.GetDataSerializer <ProtobufSerializer>();

            NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(
                DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(serializer,
                                                                            NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);

            RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, Utility.PSK);

            NetworkComms.DisableLogging();

            NetworkComms.AppendGlobalIncomingPacketHandler <LogonInfo>(LogonInfo.Header, LogonInfoHandler);
            NetworkComms.AppendGlobalIncomingPacketHandler <Login>(Login.Header, LoginHandler);
            NetworkComms.AppendGlobalIncomingPacketHandler <Pong>(Pong.Header, PongHandler);

            PeerDiscovery.EnableDiscoverable(PeerDiscovery.DiscoveryMethod.UDPBroadcast);
        }
Ejemplo n.º 6
0
        public static void Load(MainWindow mainWindow)
        {
            authentication       = new Authentication(mainWindow);
            receiveContact       = new ReceiveContact(mainWindow);
            receiveMessage       = new ReceiveMessage(mainWindow);
            receiveNudge         = new ReceiveNudge(mainWindow);
            receiveFriendRequest = new ReceiveFriendRequest(mainWindow);
            personalUserUpdate   = new PersonalUserUpdate(mainWindow);
            receiveContactDelete = new ReceiveContactDelete(mainWindow);
            connectionedClosed   = new ConnectionClosed(mainWindow);
            receiveWritingStatus = new ReceiveWritingStatus(mainWindow);

            Personal.USER_CONTACTS     = new List <UserInfo>();
            Personal.USER_INFO         = null;
            Personal.OPEN_CHAT_WINDOWS = new List <ChatWindow>();

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(),
                                                                            NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);

            RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, Config.Properties.SERVER_ENCRYPTION_KEY);
            NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Updates the configuration of this instance depending on set fields
        /// </summary>
        public void RefreshNetworkCommsConfiguration()
        {
            #region First Initialisation
            //On first initialisation we need to configure NetworkComms.Net to handle our incoming packet types
            //We only need to add the packet handlers once. If we call NetworkComms.Shutdown() at some future point these are not removed.
            if (FirstInitialisation)
            {
                FirstInitialisation = false;



                //Configure NetworkComms.Net to handle any incoming packet of type 'ChatMessage'
                //e.g. If we receive a packet of type 'ChatMessage' execute the method 'HandleIncomingChatMessage'
                NetworkComms.AppendGlobalIncomingPacketHandler <ChatMessage>("ChatMessage", HandleIncomingChatMessage);

                //Configure NetworkComms.Net to perform some action when a connection is closed
                //e.g. When a connection is closed execute the method 'HandleConnectionClosed'
                NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
            }
            #endregion

            #region Set serializer
            //Set the default send recieve options to use the specified serializer. Keep the DataProcessors and Options from the previous defaults
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(Serializer, NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);
            #endregion

            #region Optional Encryption
            //Configure encryption if requested
            if (EncryptionEnabled && !NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>()))
            {
                //Encryption is currently implemented using a pre-shared key (PSK) system
                //NetworkComms.Net supports multiple data processors which can be used with any level of granularity
                //To enable encryption globally (i.e. for all connections) we first add the encryption password as an option
                RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, _encryptionKey);
                //Finally we add the RijndaelPSKEncrypter data processor to the sendReceiveOptions
                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
            }
            else if (!EncryptionEnabled && NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>()))
            {
                //If encryption has been disabled but is currently enabled
                //To disable encryption we just remove the RijndaelPSKEncrypter data processor from the sendReceiveOptions
                NetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
            }
            #endregion

            #region Local Server Mode and Connection Type Changes
            if (LocalServerEnabled && ConnectionType == ConnectionType.TCP && !Connection.Listening(ConnectionType.TCP))
            {
                //If we were previously listening for UDP we first shutdown NetworkComms.Net.
                if (Connection.Listening(ConnectionType.UDP))
                {
                    AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");
                    NetworkComms.Shutdown();
                }
                else
                {
                    AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");
                    NetworkComms.Shutdown();
                }

                //Start listening for new incoming 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));

                //Write the IP addresses and ports that we are listening on to the chatBox
                AppendLineToChatHistory("Listening for incoming TCP connections on:");
                foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
                {
                    AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port);
                }

                //Add a blank line after the initialisation output
                AppendLineToChatHistory(System.Environment.NewLine);
            }
            else if (LocalServerEnabled && ConnectionType == ConnectionType.UDP && !Connection.Listening(ConnectionType.UDP))
            {
                //If we were previously listening for TCP we first shutdown NetworkComms.Net.
                if (Connection.Listening(ConnectionType.TCP))
                {
                    AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");
                    NetworkComms.Shutdown();
                }
                else
                {
                    AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");
                    NetworkComms.Shutdown();
                }

                //Start listening for new incoming UDP 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.UDP, new IPEndPoint(IPAddress.Any, 0));

                //Write the IP addresses and ports that we are listening on to the chatBox
                AppendLineToChatHistory("Listening for incoming UDP connections on:");
                foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP))
                {
                    AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port);
                }

                //Add a blank line after the initialisation output
                AppendLineToChatHistory(System.Environment.NewLine);
            }
            else if (!LocalServerEnabled && (Connection.Listening(ConnectionType.TCP) || Connection.Listening(ConnectionType.UDP)))
            {
                //If the local server mode has been disabled but we are still listening we need to stop accepting incoming connections
                NetworkComms.Shutdown();
                AppendLineToChatHistory("Local server mode disabled. Any existing connections will be closed.");
                AppendLineToChatHistory(System.Environment.NewLine);
            }
            else if (!LocalServerEnabled &&
                     ((ConnectionType == ConnectionType.UDP && NetworkComms.GetExistingConnection(ConnectionType.TCP).Count > 0) ||
                      (ConnectionType == ConnectionType.TCP && NetworkComms.GetExistingConnection(ConnectionType.UDP).Count > 0)))
            {
                //If we are not running a local server but have changed the connection type after creating connections we need to close
                //existing connections.
                NetworkComms.Shutdown();
                AppendLineToChatHistory("Connection mode has been changed. Existing connections will be closed.");
                AppendLineToChatHistory(System.Environment.NewLine);
            }
            #endregion
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Allows to choose different compressors
        /// </summary>
        private static void SelectDataProcessors(out List <DataProcessor> dataProcessors, out Dictionary <string, string> dataProcessorOptions)
        {
            dataProcessors       = new List <DataProcessor>();
            dataProcessorOptions = new Dictionary <string, string>();

            #region Possible Compressor
            Console.WriteLine("Would you like to include data compression?\n1 - No\n2 - Yes\n");

            int includeCompression;
            while (true)
            {
                bool parseSucces = int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out includeCompression);
                if (parseSucces && includeCompression <= 2 && includeCompression > 0)
                {
                    break;
                }
                Console.WriteLine("Invalid choice. Please try again.");
            }

            if (includeCompression == 2)
            {
                Console.WriteLine("Please select a compressor:\n1 - LZMA (Slow Speed, Best Compression)\n2 - GZip (Good Speed, Good Compression)\n3 - QuickLZ (Best Speed, Basic Compression)\n");

                int selectedCompressor;
                while (true)
                {
                    bool parseSucces = int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out selectedCompressor);
                    if (parseSucces && selectedCompressor <= 3 && selectedCompressor > 0)
                    {
                        break;
                    }
                    Console.WriteLine("Invalid compressor choice. Please try again.");
                }

                if (selectedCompressor == 1)
                {
                    Console.WriteLine(" ... selected LZMA compressor.\n");
                    dataProcessors.Add(DPSManager.GetDataProcessor <NetworkCommsDotNet.DPSBase.SevenZipLZMACompressor.LZMACompressor>());
                }
                else if (selectedCompressor == 2)
                {
                    Console.WriteLine(" ... selected GZip compressor.\n");
                    dataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());
                }
                else if (selectedCompressor == 3)
                {
                    Console.WriteLine(" ... selected QuickLZ compressor.\n");
                    dataProcessors.Add(DPSManager.GetDataProcessor <QuickLZCompressor.QuickLZ>());
                }
                else
                {
                    throw new Exception("Unable to determine selected compressor.");
                }
            }
            #endregion

            #region Possible Encryption
            Console.WriteLine("Would you like to include data encryption?\n1 - No\n2 - Yes\n");

            int includeEncryption;
            while (true)
            {
                bool parseSucces = int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out includeEncryption);
                if (parseSucces && includeEncryption <= 2 && includeEncryption > 0)
                {
                    break;
                }
                Console.WriteLine("Invalid choice. Please try again.");
            }

            if (includeEncryption == 2)
            {
                Console.Write("Please enter an encryption password and press enter: ");
                string password = Console.ReadLine();
                Console.WriteLine();

                //Use the nested packet feature so that we do not expose the packet type used.
                NetworkComms.DefaultSendReceiveOptions.UseNestedPacket = true;
                RijndaelPSKEncrypter.AddPasswordToOptions(dataProcessorOptions, password);
                dataProcessors.Add(DPSManager.GetDataProcessor <RijndaelPSKEncrypter>());
            }
            #endregion
        }
        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);
            }
        }