Beispiel #1
0
        public void Connect(IPAddress address)
        {
            this.ipAddress = address;

            try
            {
                NetworkComms.RemoveGlobalConnectionCloseHandler(HandleConnectionClosed);

                NetworkComms.Shutdown();
            }
            catch
            {
                // Just here to avoid potential crash
            }

            if (!packetsAppended)
            {
                NetworkComms.AppendGlobalIncomingPacketHandler <Custom>("Custom", ReceiveCustomPacket);
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PacketName.ReLoginResult.ToString(), ReceiveLoginResult);
                NetworkComms.AppendGlobalIncomingPacketHandler <ModuleList>(PacketName.ReModuleList.ToString(), ModuleList);
                NetworkComms.AppendGlobalIncomingPacketHandler <AppFileData>(PacketName.ReAppFile.ToString(), AppFile);
                NetworkComms.AppendGlobalIncomingPacketHandler <GroupList>(PacketName.ReUserGroupList.ToString(), GroupListReceived);
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PacketName.ReSessionVerificationResult.ToString(), SessionVerificationResultReceived);
                NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketName.ReSessionId.ToString(), SessionIdReceived);
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PacketName.ReUnauthorized.ToString(), UnAuthorizedReceived);

                packetsAppended = true;
            }

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

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

            if (Connectable(address.ToString()))
            {
                connectionInfo = new ConnectionInfo(address.ToString(), port);
            }
        }
Beispiel #2
0
        public Server()
        {
            //Trigger the method PrintIncomingMessage when a packet of type 'Message' is received
            //We expect the incoming object to be a string which we state explicitly by using <string>
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", PrintIncomingMessage);
            //Start listening for incoming connections
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 50111));

            //Print out the IPs and ports we are now listening on
            Console.WriteLine("Server listening for TCP connection on:");
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }

            //Let the user close the server
            Console.WriteLine("\nPress any key to close server.");
            Console.ReadKey(true);

            //We have used NetworkComms so we should ensure that we correctly call shutdown
            NetworkComms.Shutdown();
        }
Beispiel #3
0
        public User()
        {
            //Request server IP and port number
            Console.WriteLine("Please enter the server IP and port in the format 192.168.0.1:10000 and press return:");
            //string serverInfo = Console.ReadLine();
            string serverInfo = "127.0.0.1:50111";

            //Parse the necessary information out of the provided string
            string serverIP   = serverInfo.Split(':').First();
            int    serverPort = int.Parse(serverInfo.Split(':').Last());

            //Keep a loopcounter
            int loopCounter = 1;

            while (true)
            {
                //Write some information to the console window
                string messageToSend = "This is message #" + loopCounter;
                Console.WriteLine("Sending message to server saying '" + messageToSend + "'");

                //Send the message in a single line
                NetworkComms.SendObject("Message", serverIP, serverPort, messageToSend);

                //Check if user wants to go around the loop
                Console.WriteLine("\nPress q to quit or any other key to send another message.");
                if (Console.ReadKey(true).Key == ConsoleKey.Q)
                {
                    break;
                }
                else
                {
                    loopCounter++;
                }
            }

            //We have used comms so we make sure to call shutdown
            NetworkComms.Shutdown();
        }
Beispiel #4
0
        public void Disconnect()
        {
            while (Peers.Count > 0)
            {
                Peers.First().DisconnectAny();
            }
            while (Trackers.Count > 0)
            {
                Trackers.First().Disconnect();
            }

            t.Stop();


            PeerDiscovery.DisableDiscoverable();
            Connection.StopListening();
            NetworkComms.CloseAllConnections();
            NetworkComms.Shutdown();

            NetworkComms.Logger.Warn("===== Client stopped =====");

            Started = false;
        }
        static void Main(string[] args)
        {
            //Solicita IP y puerto del servidor
            Console.WriteLine("Por favor ingrese la direccion IP del servidor y puerto en el formato 192.168.0.1:10000 y presione enter:");
            string serverInfo = Console.ReadLine();

            //Parsea la información necesaria del string solicitado
            string serverIP   = serverInfo.Split(':').First();
            int    serverPort = int.Parse(serverInfo.Split(':').Last());

            //Keep a loopcounter
            int loopCounter = 1;

            while (true)
            {
                //Write some information to the console window
                string messageToSend = "This is message #" + loopCounter;
                Console.WriteLine("Sending message to server saying '" + messageToSend + "'");

                //Send the message in a single line
                NetworkComms.SendObject("Message", serverIP, serverPort, messageToSend);

                //Check if user wants to go around the loop
                Console.WriteLine("\nPress q to quit or any other key to send another message.");
                if (Console.ReadKey(true).Key == ConsoleKey.Q)
                {
                    break;
                }
                else
                {
                    loopCounter++;
                }
            }

            //We have used comms so we make sure to call shutdown
            NetworkComms.Shutdown();
        }
Beispiel #6
0
 private void    parsMessage(String msg)
 {
     if (msg.Contains(Macro.RESPONSE_EXPECTED_QUERY))
     {
         _responseExpected = true;
         try {
             System.Console.WriteLine(msg.Substring(Macro.RESPONSE_EXPECTED_QUERY.Count()));
         }
         catch (ArgumentOutOfRangeException)
         {
             System.Console.WriteLine("Une erreur est survenue. Le message suivant provenant du serveur peut contenir des erreurs");
             System.Console.WriteLine(msg);
         }
     }
     else if (msg.Contains(Macro.CLIENT_DISCONNECT_QUERY))
     {
         NetworkComms.Shutdown();
         _end = true;
     }
     else
     {
         System.Console.WriteLine(msg);
     }
 }
Beispiel #7
0
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler <ServerRequest>("ServerRequest", IncomingServerRequest);
            NetworkComms.AppendGlobalIncomingPacketHandler <ClientRequest>("ClientRequest", IncomingClientRequest);
            NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);
            NetworkComms.AppendGlobalConnectionEstablishHandler(ClientConnected);

            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[+] Server listening for TCP conneciotn on:");
            foreach (var endPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                var localEndPoint = (IPEndPoint)endPoint;
                Console.WriteLine("[*] {0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("\n[!] Press any key to close server.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.ReadKey(true);
            NetworkComms.Shutdown();
            System.Environment.Exit(0);
        }
Beispiel #8
0
        public static void ConfigureSockets(Message messageToSend, string serverInfo)
        {
            //Request server IP and port number
//            Console.WriteLine("Please enter the server IP and port in the format 192.168.0.1:10000 and press return:");


            //Parse the necessary information out of the provided string
            string serverIP   = serverInfo.Split(':').First();
            int    serverPort = int.Parse(serverInfo.Split(':').Last());


            //Write some information to the console window


//            NetworkComms.SendObject("Message", serverIP, serverPort, "OK");
            //            NetworkComms.SendObject("Message", serverIP, serverPort, SerializeObject<Message>(messageToSend));
            var message = getSourceNodes();

            NetworkComms.SendObject("Message", serverIP, serverPort, SerializeObject <List <SourceNode> >(message));


            //We have used comms so we make sure to call shutdown
            NetworkComms.Shutdown();
        }
Beispiel #9
0
 /// <summary>
 /// 关闭程序时,调用释放所有的资源
 /// Shutdown all connections, threads and execute OnCommsShutdown event.
 /// should be called on application close.
 /// </summary>
 public static void ShutDown()
 {
     NetworkComms.Shutdown();
 }
 /// <summary>
 /// Called before the assembly reloads -- responsible for shutting down network comms safely
 /// </summary>
 void OnBeforeAssemblyReload()
 {
     NetworkComms.Shutdown();
 }
Beispiel #11
0
 public void Disconnect()
 {
     NetworkComms.Shutdown();
 }
Beispiel #12
0
 private void MidiForwarderForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     NetworkComms.Shutdown();
 }
Beispiel #13
0
 private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     NetworkComms.Shutdown();
     GC.Collect();
     GC.WaitForPendingFinalizers();
 }
Beispiel #14
0
 /// <summary>
 /// Correctly shutdown NetworkComms .Net when closing the WPF application
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     //Ensure we shutdown comms when we are finished
     NetworkComms.Shutdown();
 }
Beispiel #15
0
 /// <summary>
 /// Called when the window is closing.
 /// </summary>
 private void WindowRegister_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     NetworkComms.Shutdown();
     this.Owner.Close();
 }
Beispiel #16
0
 // Code to execute when the application is closing (eg, user hit Back)
 // This code will not execute when the application is deactivated
 private void Application_Closing(object sender, ClosingEventArgs e)
 {
     //When the application closes it is necessary to shutdown any remaining NetworkComms activity
     NetworkComms.Shutdown();
 }
 /// <summary>
 /// callback for window closing
 /// </summary>
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     NetworkComms.Shutdown();
 }
Beispiel #18
0
 // Sent to all game objects before the application is quit
 private void OnApplicationQuit()
 {
     NetworkComms.Shutdown();
 }
 // This function is called when the MonoBehaviour will be destroyed
 private void OnDestroy()
 {
     NetworkComms.Shutdown();
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            try
            {
                Console.SetBufferSize(120, 200);
                Console.SetWindowSize(120, 25);
            }
            catch (NotImplementedException) { }

            Thread.CurrentThread.Name = "MainThread";

            Console.WriteLine("Initiating NetworkCommsDotNet examples.\n");

            //Ask user if they want to enable comms logging
            SelectLogging();

#if DEBUG
            //Set debug timeouts
            SetDebugTimeouts();
#endif

            //All we do here is let the user choice a specific example
            Console.WriteLine("Please selected an example:\n");

            //Print out the available examples
            int totalNumberOfExamples = 9;
            Console.WriteLine("1 - Basic - Message Send (Only 11 lines!)");
            Console.WriteLine();
            Console.WriteLine("2 - Intermediate - Message Send");
            Console.WriteLine("3 - Intermediate - Peer Discovery");
            Console.WriteLine();
            Console.WriteLine("4 - Advanced - Object Send");
            Console.WriteLine("5 - Advanced - Distributed File System");
            Console.WriteLine("6 - Advanced - Remote Procedure Call");
            Console.WriteLine("7 - Advanced - Unmanaged Connections");
            Console.WriteLine("8 - Advanced - TCP (SSL) Connections");
            Console.WriteLine("");
            Console.WriteLine("9 - Debug - Speed Test");

            //Get the user choice
            Console.WriteLine("");
            int selectedExample;
            while (true)
            {
                bool parseSucces = int.TryParse(Console.ReadKey().KeyChar.ToString(), out selectedExample);
                if (parseSucces && selectedExample <= totalNumberOfExamples)
                {
                    break;
                }
                Console.WriteLine("\nInvalid example choice. Please try again.");
            }

            //Clear all input so that each example can do it's own thing
            Console.Clear();

            //Run the selected example
            try
            {
                #region Run Example
                switch (selectedExample)
                {
                case 1:
                    BasicSend.RunExample();
                    break;

                case 2:
                    IntermediateSend.RunExample();
                    break;

                case 3:
                    PeerDiscoveryExample.RunExample();
                    break;

                case 4:
                    AdvancedSend.RunExample();
                    break;

                case 5:
                    DFSTest.RunExample();
                    break;

                case 6:
                    RPCExample.RunExample();
                    break;

                case 7:
                    UnmanagedConnectionExample.RunExample();
                    break;

                case 8:
                    SSLExample.RunExample();
                    break;

                case 9:
                    SpeedTest.RunExample();
                    break;

                default:
                    Console.WriteLine("Selected an invalid example number. Please restart and try again.");
                    break;
                }
                #endregion
            }
            catch (Exception ex)
            {
                //If an error was uncaught by the examples we can log the exception to a file here
                LogTools.LogException(ex, "ExampleError");
                NetworkComms.Shutdown();
                Console.WriteLine(ex.ToString());
            }

            //When we are done we give the user a chance to see all output
            Console.WriteLine("\n\nExample has completed. Please press any key to close.");
            Console.ReadKey(true);
        }
Beispiel #21
0
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            SendReceiveOptions nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), null, null);

            NetworkComms.DefaultSendReceiveOptions = nullCompressionSRO;

            //We need to define what happens when packets are received.
            //To do this we add an incoming packet handler for a 'Message' packet type.
            //
            //We will define what we want the handler to do inline by using a lambda expression
            //http://msdn.microsoft.com/en-us/library/bb397687.aspx.
            //We could also just point the AppendGlobalIncomingPacketHandler method
            //to a standard method (See AdvancedSend example)
            //
            //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 <PingRequestReturnDC>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n  ... Incoming message from " + connection.ToString() + " saying '" + incomingString.ClientID + "'-'" + incomingString.PingID + "'."); });

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

            //Print the IP addresses and ports we are listening on to make sure everything
            //worked as expected.
            Console.WriteLine("Listening for messages on:");
            foreach (System.Net.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(out targetServerConnectionInfo);

                    PingRequestReturnDC test = new PingRequestReturnDC(0, 0);

                    //There are loads of ways of sending data (see AdvancedSend example for more)
                    //but the most simple, which we use here, just uses an IP address (string) and port (integer)
                    //We pull these values out of the ConnectionInfo object we got above and voila!
                    NetworkComms.SendObject("Message", ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Address.ToString(), ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Port, test);
                }
            }

            //We should always call shutdown on comms if we have used it
            NetworkComms.Shutdown();
        }
Beispiel #22
0
 static void Main(string[] args)
 {
     NetworkManager.Start();
     Console.ReadKey();
     NetworkComms.Shutdown();
 }
        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);
        }
        /// <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
        }
Beispiel #25
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                       //
            //***************************************************************//
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler <MessageObject>("Message", Connected);
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));

            Console.WriteLine("Server listening for TCP connection on:");
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }

            createDeck();

            /*
             * int i = 0;
             * while (i < 52)
             * {
             *  Console.WriteLine("[" + deck[i].rank + " of " + deck[i].sign + "]");
             *  i++;
             * }
             * i = 0;
             * Console.WriteLine("\n////////////////////////////////\n");
             */
            Shuffle();

            /*
             * while (i < 52)
             * {
             *  Console.WriteLine("[" + deck[i].rank + " of " + deck[i].sign + "]");
             *  i++;
             * }
             */
            bool cond = true;

            while (end != true)
            {
                if (play == true)
                {
                    play = false;
                    MessageObject msg = new MessageObject("Bienvenue", "Bienvenue");
                    if (nturn >= 52)
                    {
                        msg.action = "End";
                        if (point1 > point2)
                        {
                            msg.action  = "End";
                            msg.message = "Vous avez gagné !";
                            player1.SendObject("Message", msg);
                            msg.action  = "End";
                            msg.message = "Vous avez perdu...";
                            player2.SendObject("Message", msg);
                        }
                        else if (point2 > point1)
                        {
                            msg.action  = "End";
                            msg.message = "Vous avez gagné !";
                            player2.SendObject("Message", msg);
                            msg.action  = "End";
                            msg.message = "Vous avez perdu...";
                            player1.SendObject("Message", msg);
                        }
                        else if (point1 == point2)
                        {
                            msg.action  = "End";
                            msg.message = "Egalité !";
                            player1.SendObject("Message", msg);
                            player2.SendObject("Message", msg);
                        }
                        end = true;
                    }
                    else
                    {
                        if (nplay == 1)
                        {
                            msg.action = "You";
                            if (nturn != 0)
                            {
                                msg.message = "L'adversaire a joué la carte : " + cardPlayed.card2 + "\nA vous de poser une carte...";
                            }
                            else
                            {
                                msg.message = "A vous de poser une carte...";
                            }
                            player1.SendObject("Message", msg);
                            msg.action  = "Other";
                            msg.message = "L'adversaire pose une carte...";
                            player2.SendObject("Message", msg);
                            nturn++;
                        }
                        else
                        {
                            msg.action  = "You";
                            msg.message = "L'adversaire a joué la carte : " + cardPlayed.card1 + "\nA vous de poser une carte...";
                            player2.SendObject("Message", msg);
                            msg.action  = "Other";
                            msg.message = "L'adversaire pose une carte...";
                            player1.SendObject("Message", msg);
                            nturn++;
                            while (wait != true)
                            {
                                i++;
                            }
                            if (firstPlay == true && secPlay == true)
                            {
                                check_better();
                            }
                        }
                    }
                }

                if (nbPlayers == 2)
                {
                    if (cond == true)
                    {
                        cond = false;
                        MessageObject msg = new MessageObject("Bienvenue", "Bienvenue");

                        player1.SendObject("Message", msg);
                        player2.SendObject("Message", msg);
                        msg.action = "Card";
                        int i = 0;
                        while (i < 26)
                        {
                            msg.message = "[" + deck[i].rank + " of " + deck[i].sign + "]";
                            player1.SendObject("Message", msg);
                            i++;
                        }
                        while (i < 52)
                        {
                            msg.message = "[" + deck[i].rank + " of " + deck[i].sign + "]";
                            player2.SendObject("Message", msg);
                            i++;
                        }
                        //Console.WriteLine("test\n");
                        msg.action  = "Message";
                        msg.message = "Le jeu peut commencer.";
                        player1.SendObject("Message", msg);
                        player2.SendObject("Message", msg);
                        play = true;
                        //end = true;
                    }
                }
            }
            Console.WriteLine("\nPress any key to close server.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
 private void ChatForm_Closing(object sender, EventArgs e)
 {
     // [ttaj] Turn off server/client once done.
     NetworkComms.Shutdown();
 }
Beispiel #28
0
 internal void Stop()
 {
     _Server.Shutdown("Server is shutting down...");
     NetworkComms.Shutdown();
     _WebServer.Stop();
 }
 void Application_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
 {
     NetworkComms.Shutdown();
 }
 /// <summary>
 /// Para a escuta do servidor
 /// </summary>
 public void Stop()
 {
     NetworkComms.Shutdown();
     ServerLog.Write("!.....Server desativado manualmente..................");
 }