private static void SendToServer <T>(string sendMessage, T objectToSend) where T : ServerObject
        {
            ConnectionInfo serverConnectionInfo;

            if (ip == null)
            {
                return;
            }
            try
            {
                serverConnectionInfo = new ConnectionInfo(ip, CommonInfo.ServerPort);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                //ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again");
                return;
            }

            try
            {
                TCPConnection serverConnection = TCPConnection.GetConnection(serverConnectionInfo);
                serverConnection.SendObject(sendMessage, objectToSend.SerializeToString());
            }
            catch (CommsException e)
            {
                Console.WriteLine(e.ToString());
                /*AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again.");*/
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                /*AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again.");*/
            }
        }
Exemplo n.º 2
0
        public ClientNetwork(Game ngame, string ip, int port)
        {
            Hello msg = new Hello();

            SendReceiveOptions customSendReceiveOptions = new SendReceiveOptions <ProtobufSerializer>();

            con = TCPConnection.GetConnection(new ConnectionInfo(ip, port), customSendReceiveOptions);

            NetworkComms.AppendGlobalIncomingPacketHandler <Back>("Back", processBack);
            NetworkComms.AppendGlobalIncomingPacketHandler <Msg>("Msg", processMsg);
            NetworkComms.AppendGlobalIncomingPacketHandler <InitMsg>("InitMsg", processInitMsg);
            NetworkComms.AppendGlobalIncomingPacketHandler <GameCommand>("GameCommand", processGC);

            game     = ngame;
            msg.text = game.getName();
            try
            {
                con.SendObject("Hello", msg);
            } catch (ArgumentException) {
                Console.WriteLine("Couldn't send request message. It appears to be an internal error. too bad :/");
            }  catch (ConnectionSetupException)  {
                Console.WriteLine("Couldn't send request message. Maybe the ip address is wrong or the server isn't running?");
            } catch (CommunicationException) {
                Console.WriteLine("Couldn't send request message. Maybe the ip address is wrong or the server isn't running?");
            }
            game.setCon(con);
        }
Exemplo n.º 3
0
    protected override void ThreadFunction()
    {
        try
        {
            TCPConnection conn = TCPConnection.GetConnection(connectionInfo);
            if (isPingOnly)
            {
                conn.SendObject("PING");
            }
            else
            {
                conn.SendObject("Command", command);
            }

            isConnected = true;

            //Debug.Log("Connected!");
        }
        catch (Exception ex)
        {
            isConnected = false;
            Debug.Log("Connection Error! " + ex.ToString());
        }
    }
Exemplo n.º 4
0
        // generic method to send command object to server
        private static Task SendCommandToServer(object cmdObj)
        {
            return(Task.Run(() =>
            {
                try
                {
                    TCPConnection conn = TCPConnection.GetConnection(_targetServerConnectionInfo);

                    conn.SendObject("Command", cmdObj);
                }
                catch (Exception ex)
                {
                    //throw (ex);
                }
            }));
        }
Exemplo n.º 5
0
        // generic method to send command object to client (Dashboard)
        private Task SendCommandToDashboardClient(VRCommand cmdObj)
        {
            return(Task.Run(() =>
            {
                try
                {
                    TCPConnection conn = TCPConnection.GetConnection(_targetDashboardClientConnectionInfo);

                    conn.SendObject("Command", cmdObj);
                }
                catch (Exception ex)
                {
                    logger.Info("SendCommandToDashboardClient" + ex.ToString());
                }
            }));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Connects to the server specified during instantiation. Returns false on a ConnectionSetupException and prints an error message.
        /// </summary>
        /// <returns>Success of connection.</returns>
        public bool ConnectToServer()
        {
            try
            {
                //Get a connection with the specified connectionInfo.
                _connection = TCPConnection.GetConnection(_connectionInfo);
                //Need to send a dummy message for the server to acknowledge.
                _connection.SendObject("Hello");
            }
            catch (ConnectionSetupException exception)
            {
                View.ErrorNotify("Failed to connect to server.\nPlease check connection details.", "Connection Error");
                return false;
            }

            return true;
        }
Exemplo n.º 7
0
        public static void ConnectToMaster(string ipAdress, int ipPort, ClientListenEvents clientListenEvents)
        {
            //string logFileName = Application.dataPath + "/../Client_Log_" + NetworkComms.NetworkIdentifier + ".txt";
            //var logger = new LiteLogger(LiteLogger.LogMode.LogFileOnly, logFileName);
            //NetworkComms.EnableLogging(logger);

            var serverEndPoint = new IPEndPoint(IPAddress.Parse(ipAdress), ipPort);

            clientConnection = TCPConnection.GetConnection(new ConnectionInfo(serverEndPoint));

            Debug.Log($"Established Connection: \n {clientConnection}");

            AppendClientListener(clientListenEvents);

            //Auth
            clientConnection.SendObject("LoginInfo", new LoginInfo("BetaPlayer_Null_UID"));
        }
Exemplo n.º 8
0
    protected override void ThreadFunction()
    {
        try
        {
            TCPConnection conn = TCPConnection.GetConnection(connectionInfo);
            if (isPingOnly)
            {
                command = new VRCommand(Enums.ControlMessage.NONE);
            }

            conn.SendObject("Command", command);

            //Debug.Log("Connected!");
        }
        catch (Exception ex)
        {
            Debug.Log("Connection Error! " + ex.ToString());
        }
    }
Exemplo n.º 9
0
        // generic method to send command object to server
        private Task SendCommandToServer(VRCommand cmdObj)
        {
            return(Task.Run(() =>
            {
                try
                {
                    cmdObj.MachineName = System.Environment.MachineName;
                    cmdObj.LiveClientStatus = _internalCurrentClientStatus;
                    cmdObj.AdditionalInfo = _internalAdditionalInfo;
                    TCPConnection conn = TCPConnection.GetConnection(_targetServerConnectionInfo);

                    conn.SendObject("Command", cmdObj);
                }
                catch (Exception ex)
                {
                    logger.Info("SendCommandToServer" + ex.ToString());
                }
            }));
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            SendReceiveOptions options = new SendReceiveOptions <ProtobufSerializer>();
            ConnectionInfo     conn    = new ConnectionInfo("127.0.0.1", 7777);
            TCPConnection      socket  = TCPConnection.GetConnection(conn, options);

            //response = socket.SendReceiveObject<string>("RequestLogin", "Response", int.MaxValue);
            socket.SendObject("RequestLogin");

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("RequestLoginData", (packetHeader, connection, input) =>
            {
                /*Console.WriteLine("Please enter your username: "******"Please enter your password: "******"domis045", "admin");

                connection.SendObject("LoginData", cred);

                /* connection.SendObject("LoginData", "No");
                 * Console.WriteLine(connection);
                 * //connection.Dispose();*/
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("DisconnectMessage", (packetHeader, connection, input) =>
            {
                Console.WriteLine("Your connection has been dropped by the server!");
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <int>("ConnectionMessage", (packetHeader, connection, input) =>
            {
                Console.WriteLine("You have connected sucesfully!");
            });

            Console.ReadLine();

            // Credentials _cred = connection.SendReceiveObject<Credentials>("RequestLoginData", "LoginData", int.MaxValue);
        }
Exemplo n.º 11
0
 // 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());
         }
     }));
 }
Exemplo n.º 12
0
 public static void SendMessage(string mType, TCPConnection con, byte[] obj)
 {
     Debug.Log("Sending a message to...");
     con.SendObject(mType, obj);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            //Select mode
            Console.WriteLine("SpeedTest Example ...\n");

            Console.WriteLine("Please select host or peer mode:");
            Console.WriteLine("1 - Host Mode (Catches Data)");
            Console.WriteLine("2 - Peer Mode (Sends Data)");

            //Read in user choice
            if (Console.ReadKey(true).Key == ConsoleKey.D1)
            {
                hostMode = true;
            }
            else
            {
                hostMode = false;
            }

            if (hostMode)
            {
                //Prepare DFS in host mode
                #region ServerMode
                Console.WriteLine("\n ... host mode selected.");

                NetworkComms.ConnectionEstablishShutdownDelegate clientEstablishDelegate = (connection) =>
                {
                    Console.WriteLine("Client " + connection.ConnectionInfo + " connected.");
                };

                NetworkComms.ConnectionEstablishShutdownDelegate clientShutdownDelegate = (connection) =>
                {
                    Console.WriteLine("Client " + connection.ConnectionInfo + " disconnected.");
                };

                NetworkComms.PacketHandlerCallBackDelegate <byte[]> IncomingDataDelegate = (packetHeader, connection, incomingObject) =>
                {
                    Console.WriteLine("Speed bytes received from " + connection.ConnectionInfo + ".");
                };

                NetworkComms.AppendGlobalConnectionEstablishHandler(clientEstablishDelegate);
                NetworkComms.AppendGlobalConnectionCloseHandler(clientShutdownDelegate);
                NetworkComms.AppendGlobalIncomingPacketHandler("SpeedData", IncomingDataDelegate);

                //Start listening for TCP connections
                //We want to select a random port on all available adaptors so provide
                //an IPEndPoint using IPAddress.Any and port 0.
                Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));

                Console.WriteLine("\nListening for incoming connections on:");
                foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
                {
                    Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
                }

                Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier);
                Console.WriteLine("\nPress 'q' to close host.\n");

                while (true)
                {
                    ConsoleKeyInfo pressedKey = Console.ReadKey(true);
                    if (pressedKey.Modifiers != ConsoleModifiers.Control && pressedKey.Key == ConsoleKey.Q)
                    {
                        Console.WriteLine("Closing host.");
                        break;
                    }
                }
                #endregion
            }
            else if (!hostMode)
            {
                //Prepare DFS in peer mode
                #region PeerMode
                Console.WriteLine("\n ... peer mode selected.");

                Console.WriteLine("\nPlease enter how large the test data packet should be in MB and press return (larger is more accurate), e.g. 1024:");
                int numberMegsToCreate = int.Parse(Console.ReadLine());

                //Fill a byte[] with random data
                DateTime startTime      = DateTime.Now;
                Random   randGen        = new Random();
                byte[]   someRandomData = new byte[numberMegsToCreate * 1024 * 1024];
                randGen.NextBytes(someRandomData);

                Console.WriteLine("\nTest speed data created. Using {0}MB.\n", numberMegsToCreate);

                NetworkComms.PacketConfirmationTimeoutMS = 20000;
                ConnectionInfo serverConnectionInfo = ExampleHelper.GetServerDetails();

                Console.WriteLine("\nIdentifier - {0}", NetworkComms.NetworkIdentifier);

                SendReceiveOptions nullCompressionSRO = new SendReceiveOptions <NullSerializer>();

                //Add options which will require receive confirmations and also include packet construction time
                //in the packet header.
                nullCompressionSRO.Options.Add("ReceiveConfirmationRequired", "");
                nullCompressionSRO.Options.Add("IncludePacketConstructionTime", "");

                TCPConnection serverConnection = TCPConnection.GetConnection(serverConnectionInfo);
                Stopwatch     timer            = new Stopwatch();

                while (true)
                {
                    timer.Reset();
                    timer.Start();
                    serverConnection.SendObject("SpeedData", someRandomData, nullCompressionSRO);
                    timer.Stop();
                    Console.WriteLine("SpeedData sent successfully with receive confirmation in {0}secs. Corresponds to {1}MB/s", (timer.ElapsedMilliseconds / 1000.0).ToString("0.00"), (numberMegsToCreate / (timer.ElapsedMilliseconds / 1000.0)).ToString("0.00"));
                }
                #endregion
            }

            NetworkComms.Shutdown();
        }
Exemplo n.º 14
0
        //Dictionary<ShortGuid, NetworkSendObject> lastPeerSendObjectDict = new Dictionary<ShortGuid, NetworkSendObject>();
        public static bool SendNetworkObject(object objToSend, string comment = null, string ip = null, string port = null)
        {
            bool successful = false;

            if (objToSend != null)
            {
                NetworkSendObject networkSendObject = new NetworkSendObject();
                switch (objToSend)
                {
                case Guid g:
                    networkSendObject.GuidValue = g;
                    break;

                /*
                 *  case SignInRecord sir:
                 *      networkSendObject.signInRecord = sir;
                 *      break;*/
                case TeamMember member:
                    networkSendObject.teamMember = member;
                    break;

                case List <TeamMember> memberList:
                    networkSendObject.memberList = memberList;
                    break;
                }
                networkSendObject.RequestID        = Guid.NewGuid();
                networkSendObject.objectType       = objToSend.GetType().ToString();
                networkSendObject.SourceName       = HostInfo.HostName;
                networkSendObject.SourceIdentifier = NetworkComms.NetworkIdentifier;
                networkSendObject.comment          = comment;


                string iptouse   = ip;
                int    porttouse = int.Parse(port);
                if (ip != null)
                {
                    iptouse = ip;
                }
                if (port != null)
                {
                    int.TryParse(port, out porttouse);
                }
                DateTime today = DateTime.Now;

                //We may or may not have entered some server connection information
                ConnectionInfo serverConnectionInfo = null;
                if (!string.IsNullOrEmpty(iptouse))
                {
                    try { serverConnectionInfo = new ConnectionInfo(iptouse, porttouse); }
                    catch (Exception)
                    {
                        //addToNetworkLog(string.Format(Globals.cultureInfo, "{0:HH:mm:ss}", today) + " Error - Failed to parse the server IP and port. Please ensure it is correct and try again\r\n\r\n");
                        //MessageBox.Show("Failed to parse the server IP and port. Please ensure it is correct and try again", "Server IP & Port Parse Error", MessageBoxButtons.OK);
                        return(false);
                    }
                }
                // ShortGuid networkIdentifier = ShortGuid.NewGuid();

                //lock (lastPeerSendObjectDict) lastPeerSendObjectDict[networkIdentifier] = networkSendObject;

                //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
                    {
                        //ProtobufSerializer serializer = new ProtobufSerializer();
                        SendReceiveOptions sendReceiveOptions = new SendReceiveOptions <ProtobufSerializer>();

                        TCPConnection connection = TCPConnection.GetConnection(serverConnectionInfo);
                        connection.SendObject("NetworkSendObject", networkSendObject);
                        successful = true;
                        // addToNetworkLog(string.Format(Globals.cultureInfo, "{0:HH:mm:ss}", today) + " - sent " + networkSendObject.objectType + " - " + networkSendObject.comment + "\r\n");
                    }

                    catch (Exception ex)
                    {
                        return(false);
                        //addToNetworkLog(string.Format(Globals.cultureInfo, "{0:HH:mm:ss}", today) + " Error - " + ex.ToString() + "\r\n\r\n");
                        // MessageBox.Show("A CommsException occurred while trying to send a " + networkSendObject.GetType() + " to " + ex.ToString(), "CommsException", MessageBoxButtons.OK);
                    }
                }

                return(successful);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 15
0
        private static void OnConnected()
        {
            if (diffieHellman != null)
            {
                diffieHellman.Dispose();
            }

            diffieHellman = new ECDiffieHellmanCng();
            byte[] servicePublicPart = diffieHellman.PublicKey.ToByteArray();
            using (MemoryStream sendStream = new MemoryStream(servicePublicPart.Length + 2))
            {
                using (BinaryWriter writer = new BinaryWriter(sendStream))
                {
                    writer.Write((ushort)servicePublicPart.Length);
                    writer.Write(servicePublicPart);
                }
                connection.SendObject <byte[]>("Handshake", sendStream.GetBuffer());
                connection.AppendIncomingPacketHandler <byte[]>("HandshakeResponse", (header, connection, bytes) =>
                {
                    connection.RemoveIncomingPacketHandler("HandshakeResponse");
                    using (MemoryStream receiveStream = new MemoryStream(bytes))
                    {
                        using (BinaryReader reader = new BinaryReader(receiveStream))
                        {
                            ushort saltLength      = reader.ReadUInt16();
                            byte[] salt            = reader.ReadBytes(saltLength);
                            ushort keyBlobLength   = reader.ReadUInt16();
                            byte[] keyBlob         = reader.ReadBytes(keyBlobLength);
                            ushort signatureLength = reader.ReadUInt16();
                            byte[] signature       = reader.ReadBytes(signatureLength);

                            using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                            {
                                try
                                {
                                    StringReader stringReader = new StringReader(Properties.Resources.publickey);
                                    XmlSerializer serializer  = new XmlSerializer(typeof(RSAParameters));
                                    RSAParameters rsaParams   = (RSAParameters)serializer.Deserialize(stringReader);
                                    csp.ImportParameters(rsaParams);
                                    if (!csp.VerifyData(keyBlob, new SHA512CryptoServiceProvider(), signature))
                                    {
                                        //Something is wrong here. The public blob does not match the signature. Possible MITM.
                                        connection.CloseConnection(true);
                                        connection = null;
                                    }
                                    else
                                    {
                                        //Connection was fine. Key exchange worked. Let's set the encryption up!
                                        byte[] sharedMaterial = diffieHellman.DeriveKeyMaterial(CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob));
                                        using (Rfc2898DeriveBytes keyDerive = new Rfc2898DeriveBytes(sharedMaterial, salt, 1000))
                                        {
                                            encryptionKey = keyDerive.GetBytes(32); // 32 bytes = 256 bits, for AES encryption. Salt is generated per message
                                        }
                                        SetupMessageHandlers();
                                    }
                                }
                                finally
                                {
                                    csp.PersistKeyInCsp = false;
                                    if (diffieHellman != null)
                                    {
                                        diffieHellman.Dispose();
                                        diffieHellman = null;
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
Exemplo n.º 16
0
        /// <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 void TestMethodClientTracker()
        {
            NetworkComms.EnableLogging();
            NetworkComms.Shutdown();

            int myPort = CommonHelpers.PeerPort + 2;

            VotingsUser.PeerDiscovery = true;

            Tracker        tracker1    = null;
            TCPConnection  our         = null;
            List <Tracker> allTrackers = null;


            int connToPeer  = 0;
            int toPeer      = 0;
            int reqPeers    = 0;
            int peersEvent  = 0;
            int blocksEvent = 0;



            //============

            //прослушиваем 2 порта
            TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(myPort, true));                 //мы
            TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(CommonHelpers.PeerPort, true)); //они


            allTrackers = new List <Tracker>();
            tracker1    = new Tracker(CommonHelpers.GetLocalEndPoint(myPort), allTrackers);
            allTrackers.Add(tracker1);

            //получаем подключение пира к нам
            NetworkComms.AppendGlobalConnectionEstablishHandler((c) =>
            {
                our = c as TCPConnection;
            });

            //определяем, что сообщения пришли

            NetworkComms.AppendGlobalIncomingPacketHandler <ConnectToPeerWithTrackerMessage>(typeof(ConnectToPeerWithTrackerMessage).Name, (p, c, i) =>
            {
                connToPeer++;
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <ToPeerMessage>(typeof(ToPeerMessage).Name, (p, c, i) =>
            {
                toPeer++;
            });


            NetworkComms.AppendGlobalIncomingPacketHandler <RequestPeersMessage>(typeof(RequestPeersMessage).Name, (p, c, i) =>
            {
                reqPeers++;
            });



            tracker1.OnBlocksMessage += (s, e) =>
            {
                blocksEvent++;
            };



            tracker1.OnRequestPeersMessage += (s, e) =>
            {
                peersEvent++;
            };



            //============


            //подключаемся к пиру
            tracker1.Connect();
            w();
            Assert.IsTrue(tracker1.Status == TrackerStatus.Connected);



            //запрашиваем пиры у нас
            tracker1.RequestPeersFromTracker(10);
            w();
            Assert.IsTrue(reqPeers == 1);


            //отправляем сообщение нам
            tracker1.SendMessageToPeer(
                new RequestBlocksMessage(new List <string>()),
                new Peer(new IPEndPoint(0, 0),
                         new List <Peer>()));
            w();
            Assert.IsTrue(toPeer == 1);

            //запрашиваем пиры у пира
            our.SendObject <ToPeerMessage>(
                typeof(ToPeerMessage).Name,
                new ToPeerMessage(new IPEndPoint(0, 0),
                                  CommonHelpers.GetLocalEndPoint(CommonHelpers.PeerPort, true), new RequestPeersMessage(10)));
            w();
            Assert.IsTrue(peersEvent == 1);



            //отправляем блоки пиру
            our.SendObject <ToPeerMessage>(
                typeof(ToPeerMessage).Name,
                new ToPeerMessage(new IPEndPoint(0, 0),
                                  CommonHelpers.GetLocalEndPoint(CommonHelpers.PeerPort, true), new BlocksMessage()));
            w();
            Assert.IsTrue(blocksEvent == 1);


            //отправляем подключение к пиру нам
            tracker1.ConnectPeerToPeer(new Peer(new IPEndPoint(0, 0), new List <Peer>()));
            w();
            Assert.IsTrue(connToPeer == 1);


            //дисконнект от трекера
            tracker1.Disconnect();
            w();
            Assert.IsTrue(allTrackers.Count == 0);
        }
        public void TestMethodClientPeer()
        {
            NetworkComms.EnableLogging();
            NetworkComms.Shutdown();

            int    theirPort = CommonHelpers.PeerPort + 2;
            string hash      = "hash1";

            VotingsUser.PeerDiscovery = true;

            Peer          peer1    = null;
            TCPConnection our      = null;
            List <Peer>   allPeers = null;


            int reqHash        = 0;
            int reqPeers       = 0;
            int reqBlocks      = 0;
            int respPeers      = 0;
            int blocksEvent    = 0;
            int trsEvent       = 0;
            int blocksReqEvent = 0;
            int trsReqEvent    = 0;


            //============

            //прослушиваем 2 порта
            TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(CommonHelpers.PeerPort, true)); //мы
            TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(theirPort, true));              //они


            allPeers = new List <Peer>();
            peer1    = new Peer(CommonHelpers.GetLocalEndPoint(theirPort, true), allPeers);
            allPeers.Add(peer1);

            //получаем подключение пира к нам
            NetworkComms.AppendGlobalConnectionEstablishHandler((c) =>
            {
                our = c as TCPConnection;
            });



            //определяем, что сообщения пришли
            NetworkComms.AppendGlobalIncomingPacketHandler <PeerHashMessage>(typeof(PeerHashMessage).Name, (p, c, i) =>
            {
                reqHash++;
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <RequestPeersMessage>(typeof(RequestPeersMessage).Name, (p, c, i) =>
            {
                reqPeers++;
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <RequestBlocksMessage>(typeof(RequestBlocksMessage).Name, (p, c, i) =>
            {
                reqBlocks++;
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <PeersMessage>(typeof(PeersMessage).Name, (p, c, i) =>
            {
                respPeers++;
            });


            peer1.OnBlocksMessage += (s, e) =>
            {
                blocksEvent++;
            };

            peer1.OnTransactionsMessage += (s, e) =>
            {
                trsEvent++;
            };

            peer1.OnRequestBlocksMessage += (s, e) =>
            {
                blocksReqEvent++;
            };

            peer1.OnRequestTransactionsMessage += (s, e) =>
            {
                trsReqEvent++;
            };


            //============


            //подключаемся к пиру
            peer1.Connect();
            w();
            Assert.IsTrue(peer1.Status == PeerStatus.NoHashRecieved);
            Assert.IsTrue(reqHash == 1);


            //отправляем хеш пиру
            our.SendObject <PeerHashMessage>(typeof(PeerHashMessage).Name, new PeerHashMessage(hash, false));
            w();
            Assert.IsTrue(peer1.Hash == hash);
            Assert.IsTrue(peer1.Status == PeerStatus.Connected);

            //отправляем сообщение нам
            peer1.SendMessage(new RequestBlocksMessage(new List <string>()));
            w();
            Assert.IsTrue(reqBlocks == 1);

            //проверяем подключение
            peer1.CheckConnection();
            w();
            Assert.IsTrue(peer1.ErrorsCount == 0);

            //запрашиваем пиры у нас
            peer1.RequestPeers(10);
            w();
            Assert.IsTrue(reqPeers == 1);


            //запрашиваем пиры у пира
            our.SendObject <RequestPeersMessage>(typeof(RequestPeersMessage).Name, new RequestPeersMessage(10));
            w();
            Assert.IsTrue(reqPeers == 2);
            Assert.IsTrue(respPeers == 1);

            //отправляем блоки пиру
            our.SendObject <BlocksMessage>(typeof(BlocksMessage).Name, new BlocksMessage());
            w();
            Assert.IsTrue(blocksEvent == 1);

            //отправляем транзакции пиру
            our.SendObject <TransactionsMessage>(typeof(TransactionsMessage).Name, new TransactionsMessage());
            w();
            Assert.IsTrue(trsEvent == 1);

            //запрашиваем транзакции у пира
            our.SendObject <RequestTransactionsMessage>(typeof(RequestTransactionsMessage).Name, new RequestTransactionsMessage());
            w();
            Assert.IsTrue(trsReqEvent == 1);

            //запрашиваем транзакции у пира
            our.SendObject <RequestBlocksMessage>(typeof(RequestBlocksMessage).Name, new RequestBlocksMessage());
            w();
            Assert.IsTrue(blocksReqEvent == 1);


            //отключаемся от пира
            peer1.DisconnectAny();
            w();
            Assert.IsTrue(allPeers.Count == 0);
        }
Exemplo n.º 19
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();
        }