static void Main(string[] args)
        {
            string messageToSend     = "This is a message To Send";
            string messageFromServer = UDPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000), UDPOptions.None).SendReceiveObject <string>("Message", "Message", 2000, messageToSend);

            Console.WriteLine("Server said '{0}'.", messageFromServer);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
Exemple #2
0
        public static bool To(string ip, int timeout = 10000)
        {
            var conn = UDPConnection.GetConnection(new ConnectionInfo(ip, Port), UDPOptions.Handshake, true, false);

            try {
                conn.EstablishConnection();
            } catch (Exception e) {
                return(false);
            }
            conn.CloseConnection(false);
            return(true);
        }
Exemple #3
0
        private UDPConnection CreateUDPConnection()
        {
            try
            {
                var connectionInfo = new ConnectionInfo(ConnectionType.UDP, ShortGuid.NewGuid(), new IPEndPoint(IPAddress.Any, 0), true);
                var connection     = UDPConnection.GetConnection(connectionInfo, UDPOptions.None);

                return(connection);
            }
            catch (Exception ex)
            {
                Trace.TraceError("[ UDP ] CreateLocalUDPConnection, Error = {0}", ex.Message);
            }

            return(null);
        }
Exemple #4
0
        public Client()
        {
            // Set connection to server
            Console.WriteLine("Please enter the server IP:port");
            var serverInfo = Console.ReadLine();
            var serverIp   = serverInfo.Split(':').First();
            var serverPort = int.Parse(serverInfo.Split(':').Last());
            var connInfo   = new ConnectionInfo(serverIp, serverPort);

            ClientConnection = UDPConnection.GetConnection(connInfo, UDPOptions.None);

            // Handlers
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("message", WriteMessage);
            NetworkComms.AppendGlobalIncomingPacketHandler <int>("clientId", SetId);

            // Send my name to server
            Console.WriteLine("Please enter your name:");
            var name = Console.ReadLine();

            ClientConnection.SendObject("Name", name);
        }
 // generic method to send command object to ManageSystem
 private Task SendCommandToPeer(ConnectionInfo connectionInfo, object cmdObj)
 {
     return(Task.Run(() =>
     {
         try
         {
             if (connectionInfo.ConnectionType == ConnectionType.TCP)
             {
                 TCPConnection conn = TCPConnection.GetConnection(connectionInfo);
                 conn.SendObject("Command", cmdObj);
             }
             else if (connectionInfo.ConnectionType == ConnectionType.UDP)
             {
                 UDPConnection conn = UDPConnection.GetConnection(connectionInfo, UDPOptions.None);
                 conn.SendObject("Command", cmdObj);
             }
         }
         catch (Exception ex)
         {
             logger.Info("SendCommandToPeer: Remote[" + connectionInfo.RemoteEndPoint.ToString() + "] Local[" + connectionInfo.LocalEndPoint.ToString() + "] TypeofcmdObj[" + cmdObj.GetType().ToString() + "] Error:" + ex.ToString());
         }
     }));
 }
Exemple #6
0
        /// <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>
        /// Send a message.
        /// </summary>
        public void SendMessage(string stringToSend)
        {
            //If we have tried to send a zero length string we just return
            if (stringToSend.Trim() == "")
            {
                return;
            }

            //We may or may not have entered some server connection information
            ConnectionInfo serverConnectionInfo = null;

            if (ServerIPAddress != "")
            {
                try { serverConnectionInfo = new ConnectionInfo(ServerIPAddress, ServerPort); }
                catch (Exception)
                {
                    ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again");
                    return;
                }
            }

            //We wrap everything we want to send in the ChatMessage class we created
            ChatMessage chatMessage = new ChatMessage(NetworkComms.NetworkIdentifier, LocalName, stringToSend, messageSendIndex++);

            //We add our own message to the message history in case it gets relayed back to us
            lock (lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] = chatMessage;

            //We write our own message to the chatBox
            AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message);

            //Clear the input box text
            ClearInputLine();

            //If we provided server information we send to the server first
            if (serverConnectionInfo != null)
            {
                //We perform the send within a try catch to ensure the application continues to run if there is a problem.
                try
                {
                    if (ConnectionType == ConnectionType.TCP)
                    {
                        TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", chatMessage);
                    }
                    else if (ConnectionType == ConnectionType.UDP)
                    {
                        UDPConnection.GetConnection(serverConnectionInfo, UDPOptions.None).SendObject("ChatMessage", chatMessage);
                    }
                    else
                    {
                        throw new Exception("An invalid connectionType is set.");
                    }
                }
                catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); }
                catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); }
            }

            //If we have any other connections we now send the message to those as well
            //This ensures that if we are the server everyone who is connected to us gets our message
            //We want a list of all established connections not including the server if set
            List <ConnectionInfo> otherConnectionInfos;

            if (serverConnectionInfo != null)
            {
                otherConnectionInfos = (from current in NetworkComms.AllConnectionInfo() where current.RemoteEndPoint != serverConnectionInfo.RemoteEndPoint select current).ToList();
            }
            else
            {
                otherConnectionInfos = NetworkComms.AllConnectionInfo();
            }

            foreach (ConnectionInfo info in otherConnectionInfos)
            {
                //We perform the send within a try catch to ensure the application continues to run if there is a problem.
                try
                {
                    if (ConnectionType == ConnectionType.TCP)
                    {
                        TCPConnection.GetConnection(info).SendObject("ChatMessage", chatMessage);
                    }
                    else if (ConnectionType == ConnectionType.UDP)
                    {
                        UDPConnection.GetConnection(info, UDPOptions.None).SendObject("ChatMessage", chatMessage);
                    }
                    else
                    {
                        throw new Exception("An invalid connectionType is set.");
                    }
                }
                catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + info + ". Please check settings and try again."); }
                catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + info + ". Please check settings and try again."); }
            }

            return;
        }
Exemple #8
0
        /// <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>
        /// Hammers the server with connections.
        /// </summary>
        private static void ConnectionHammer(int index)
        {
            Random rand = new Random(index);

            for (int i = 0; i < connectionsPerHammer; i++)
            {
                bool tcpSelected = false;
                if (TCPServerEndPointsKeys.Count > 0 && UDPServerEndPointsKeys.Count > 0)
                {
                    tcpSelected = (rand.NextDouble() > 0.5);
                }
                else if (TCPServerEndPointsKeys.Count > 0)
                {
                    tcpSelected = true;
                }

                //options.Options.Add("ReceiveConfirmationRequired", "");

                IPEndPoint     selectedEndPoint;
                ConnectionInfo connInfo;
                if (tcpSelected)
                {
                    selectedEndPoint = TCPServerEndPointsKeys[(int)(TCPServerEndPoints.Count * rand.NextDouble())];
                    connInfo         = new ConnectionInfo(selectedEndPoint, TCPServerEndPoints[selectedEndPoint]);
                }
                else
                {
                    selectedEndPoint = UDPServerEndPointsKeys[(int)(UDPServerEndPoints.Count * rand.NextDouble())];
                    connInfo         = new ConnectionInfo(selectedEndPoint, UDPServerEndPoints[selectedEndPoint]);
                }

                try
                {
                    Connection conn;

                    if (tcpSelected)
                    {
                        conn = TCPConnection.GetConnection(connInfo, sendReceiveOptions);
                        conn.SendObject(packetTypeStr, clientHammerData);

                        if (closeConnectionAfterSend)
                        {
                            conn.CloseConnection(false);
                        }
                    }
                    else
                    {
                        conn = UDPConnection.GetConnection(connInfo, UDPConnection.DefaultUDPOptions, sendReceiveOptions);
                        conn.SendObject(packetTypeStr, clientHammerData);

                        if (closeConnectionAfterSend)
                        {
                            conn.CloseConnection(false);
                        }

                        //SendReceiveOptions unmanagedOptions = new SendReceiveOptions<NullSerializer>();
                        //UDPConnection.SendObject("Unmanaged", clientHammerData, connInfo.RemoteEndPoint, unmanagedOptions, connInfo.ApplicationLayerProtocol);
                    }
                }
                catch (CommsException ex)
                {
                    Interlocked.Increment(ref exceptionCount);
                    LogTools.AppendStringToLogFile("ClientExceptions", ex.ToString());
                }
            }
        }
Exemple #10
0
            /// <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();
                }
            }