private static void RunServer()
        {
            //ILogger logger = new LiteLogger(LiteLogger.LogMode.LogFileOnly, "DebugTests_" + NetworkComms.NetworkIdentifier + ".txt");
            //NetworkComms.EnableLogging(logger);

            //Slightly improves performance when we have many simultaneous incoming connections.
            NetworkComms.ConnectionListenModeUseSync = true;

            //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);
            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished);
            NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);

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

            //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();
        }
        private void InitNetworkComms()
        {
            _targetClientDaemonConnection   = new List <ConnectionInfo>();
            _targetManagingSystemConnection = new List <ConnectionInfo>();

            DataSerializer              dataSerializer       = DPSManager.GetDataSerializer <ProtobufSerializer>();
            List <DataProcessor>        dataProcessors       = new List <DataProcessor>();
            Dictionary <string, string> dataProcessorOptions = new Dictionary <string, string>();

            SendReceiveOptions noCompressionSRO = new SendReceiveOptions(dataSerializer, new List <DataProcessor>(), dataProcessorOptions);

            //dataProcessors.Add(DPSManager.GetDataProcessor<QuickLZCompressor.QuickLZ>());
            dataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions);
            NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true;
            NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority         = QueueItemPriority.AboveNormal;

            List <ConnectionListenerBase> ClientDaemonListenList   = Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 20018)); // listen on 20018 for client daemon
            List <ConnectionListenerBase> ManagingSystemListenList = Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 20019)); // listen on 20019 for managing system

            ClientDaemonListenList.ForEach(x => x.AppendIncomingPacketHandler <VRCommand>("Command", HandleIncomingCommandClientDaemon));
            ManagingSystemListenList.ForEach(x => x.AppendIncomingPacketHandler <VRCommandServer>("Command", HandleIncomingCommandManagingSystem));


            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleClientConnectionEstablished);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleClientConnectionClosed);

            NetworkComms.ConnectionListenModeUseSync = true;
        }
Example #3
0
 public ServiceProxy(string hostname)
 {
     NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished, true);
     NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);
     NetworkComms.IgnoreUnknownPacketTypes = false;
     // NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions<NetworkingDataContracts.NetworkingDataContractSerializer>();
 }
Example #4
0
        private void InitNetworkComms()
        {
            DataSerializer              dataSerializer       = DPSManager.GetDataSerializer <ProtobufSerializer>();
            List <DataProcessor>        dataProcessors       = new List <DataProcessor>();
            Dictionary <string, string> dataProcessorOptions = new Dictionary <string, string>();

            dataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions);
            NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true;
            NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority         = QueueItemPriority.AboveNormal;


            List <ConnectionListenerBase> GameSelectorUIListenList = Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Loopback, 20015)); // listen on 20015 for local UI client
            List <ConnectionListenerBase> DashboardListenList      = Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Loopback, 20016)); // listen on 20016 for local Dashboard client

            GameSelectorUIListenList.ForEach(x => x.AppendIncomingPacketHandler <VRCommand>("Command", HandleIncomingCommandClientUI));
            DashboardListenList.ForEach(x => x.AppendIncomingPacketHandler <VRCommand>("Command", HandleIncomingCommandDashboard));

            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleGlobalConnectionEstablished);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleGlobalConnectionClosed);

            IPEndPoint ip = IPTools.ParseEndPointFromString(Utility.GetCoreConfig("ServerIPPort"));

            _targetServerConnectionInfo = new ConnectionInfo(ip, ApplicationLayerProtocolStatus.Enabled);
        }
Example #5
0
        /// <summary>
        /// 开启监听
        /// </summary>
        public static void Start()
        {
            //Add an incoming packet handler using default SendReceiveOptions.
            // Multiple  handlers for the same packet type will be executed in the order they are added.
            //注册接收到消息的处理器
            //PacketType用于标志哪种类型的消息,客户端和服务器端协议商定,标志消息类型,可以自定义
            //事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketType, PacketHandlerAction);
            //连接建立监听 事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalConnectionEstablishHandler(ConnectionEstablishDelegate);
            //连接关闭监听 事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalConnectionCloseHandler(ConnectionShutdownDelegate);
            //未处理的信息包处理 事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalIncomingUnmanagedPacketHandler(UnmanagedPacketHandlerDelgatePointer);


            //检查连接的保活的定时器时间间隔  单位秒 默认是30s
            //Connection.ConnectionKeepAlivePollIntervalSecs = 180;
            //在serverPort上开始监听消息,并返回监听的列表
            List <ConnectionListenerBase> listenerList = Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, serverPort));

            Console.WriteLine("服务器监听下列地址:");
            foreach (var listenerItem in listenerList)
            {
                Console.WriteLine(listenerItem.LocalListenEndPoint);
            }
        }
        private static void InitNetworkComms()
        {
            DataSerializer              dataSerializer       = DPSManager.GetDataSerializer <ProtobufSerializer>();
            List <DataProcessor>        dataProcessors       = new List <DataProcessor>();
            Dictionary <string, string> dataProcessorOptions = new Dictionary <string, string>();

            dataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>());
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions);
            NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true;
            NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority         = QueueItemPriority.AboveNormal;

            NetworkComms.AppendGlobalIncomingPacketHandler <VRCommandServer>("Command", HandleGlobalIncomingCommand);

            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleGlobalConnectionEstablishEvent);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleGlobalConnectionCloseEvent);

            IPEndPoint ip = IPTools.ParseEndPointFromString(Utility.GetCoreConfig("ServerIPPort"));

            _targetServerConnectionInfo = new ConnectionInfo(ip, ApplicationLayerProtocolStatus.Enabled);


            _timerPing          = new System.Timers.Timer();
            _timerPing.Elapsed += new ElapsedEventHandler(OnTimerPingEvent);
            _timerPing.Interval = 3000;
            _timerPing.Enabled  = true;
        }
Example #7
0
        public void Start()
        {
            //NetworkCommsDotNet.DPSBase.RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, "_MASSIVE123");
            Log("Encryption active", 2);
            DataSerializer dataSerializer = DPSManager.GetDataSerializer <ProtobufSerializer>();;

            Log("Data SerializeR:" + dataSerializer.ToString(), UTILITY);
            List <DataProcessor> dataProcessors = new List <DataProcessor>();

            //dataProcessors.Add(DPSManager.GetDataProcessor<QuickLZ>());

            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleConnection);
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", MessageReceived);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);

            IPAddress ip = IPAddress.Parse(ServerIPAddress);

            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(ip, ServerPort));
            Log("Listening for TCP messages on:", UTILITY);
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Log(localEndPoint.Address + ":" + localEndPoint.Port.ToString(), UTILITY);
            }

            Log("Data Directory is:" + Path.Combine(Directory.GetCurrentDirectory(), "data"), UTILITY);

            MExternalIPSniffer.SniffIP();
        }
Example #8
0
        public void Connect()
        {
            //Trigger the method PrintIncomingMessage when a packet of type 'Network' is received
            NetworkComms.AppendGlobalIncomingPacketHandler <Network>("Network", PrintIncomingMessage);
            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished);
            NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);

            Thread.Sleep(net.SLEEP);
            //Start listening for incoming connections
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 2222));

            //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);
            }

            Console.WriteLine("\ntype quit' to close server.");
            while (Console.ReadLine() != "quit")
            {
                ;
            }
            //We have used NetworkComms so we should ensure that we correctly call shutdown
            NetworkComms.Shutdown();
        }
Example #9
0
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {
            if (isInited == true)
            {
                return;
            }
            //Add an incoming packet handler using default SendReceiveOptions.
            // Multiple  handlers for the same packet type will be executed in the order they are added.
            //注册接收到消息的处理器   //PacketType用于标志哪种类型的消息,客户端和服务器端协议商定,标志消息类型,可以自定义
            //事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketType, PacketHandlerAction);

            //客户端建立连接事件
            //事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalConnectionEstablishHandler(ConnectionEstablishDelegate);
            //关闭连接事件
            //事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalConnectionCloseHandler(ConnectionShutdownDelegate);
            //未处理的信息包处理
            //事件是在多线程中回调的,不能实现确定回调的线程
            NetworkComms.AppendGlobalIncomingUnmanagedPacketHandler(UnmanagedPacketHandlerDelgatePointer);


            isInited = true;
        }
Example #10
0
        public static bool StartClient(string Hostname, int Port, string Password)
        {
            try
            {
                logger.Info("Trying to connect to Server");
                _Password = Password;
                isServer  = false;

                IPAddress ipAddress = null;
                try
                {
                    ipAddress = IPAddress.Parse(Hostname);
                }
                catch (FormatException)
                {
                    // Improperly formed IP address.
                    // Try resolving as a domain.
                    ipAddress = Dns.GetHostEntry(Hostname).AddressList[0];
                }

                ConnectionInfo serverInfo = new ConnectionInfo(ipAddress.ToString(), Port);
                NetworkComms.AppendGlobalConnectionEstablishHandler(HandleNewConnection, false);
                NetworkComms.AppendGlobalIncomingPacketHandler <iRTVOMessage>("iRTVOMessage", HandleIncomingMessage);
                NetworkComms.AppendGlobalIncomingPacketHandler <object>("iRTVOAuthenticate", HandleAuthenticateRequest);
                NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
                TCPConnection.GetConnection(serverInfo, true);
            }
            catch (Exception ex)
            {
                logger.Error("Failed to connect to Server: {0}", ex.Message);
                return(false);
            }
            return(true);
        }
 public ClientNetwork(string ip, int port)
 {
     _serverIp   = ip;
     _serverPort = port;
     NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished);
     NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);
 }
 public NetworkManager(string serverIp, int serverPort, User user)
 {
     NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEtablished);
     NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);
     addPacketHandlers();
     ServerPort = serverPort;
     _user      = user;
     ServerIp   = serverIp;
     Server     = TCPConnection.GetConnection(new ConnectionInfo(ServerIp, ServerPort));
 }
Example #13
0
        public Network()
        {
            Trackers = new List <Tracker>();
            Peers    = new List <Peer>();


            t          = new Timer(CommonHelpers.PeersCheckInterval);
            t.Elapsed += (s, e) => RequestPeers();
            t.Elapsed += (s, e) => ConnectToPeers();
            t.Elapsed += (s, e) => ConnectToTrackers();
            t.Elapsed += (s, e) => CheckPeers();

            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectPeerDirect);
        }
Example #14
0
        /// <summary>
        /// Main function
        /// </summary>
        static void Main()
        {
            try
            {
#if HAS_SSL
                SSL _ssl = new SSL("coinche_srv.pfx");
#endif

                // Register packets handler
                NetworkComms.AppendGlobalConnectionEstablishHandler(AddClient);
                NetworkComms.AppendGlobalConnectionCloseHandler(RemoveClient);

#if HAS_SSL
                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,
                                                                                                                    _ssl.ListenerOptions))).ToList();

                // Start listening for connections
                Connection.StartListening(listeners, desiredlocalEndPoints, true);
#else
                Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));
#endif

                // 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);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            finally
            {
                // 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();
            }
        }
        public NetworkManager(string ip, int port)
        {
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(BitConverter.ToInt32(IPAddress.Parse(ip).GetAddressBytes(), 0), port));
            //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);
            }

            NetworkComms.AppendGlobalConnectionEstablishHandler(NewClientConnectionHandler);
            NetworkComms.AppendGlobalConnectionCloseHandler(ShutdownConnectionHandler);

//            NetworkComms.GetExistingConnection();
        }
Example #16
0
        public Server(UInt16 port, UInt16 maxClient = 40)
        {
            MaxClient = maxClient;
            NetworkComms.AppendGlobalConnectionEstablishHandler(connectionHandler);
            NetworkComms.AppendGlobalConnectionCloseHandler(disconnectionHandler);

            NetworkComms.AppendGlobalIncomingPacketHandler <Component <Bet> >("Bet", receiveBet);

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

            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }
        }
Example #17
0
 public Server(string IpAddress, int port)
 {
     Console.WriteLine("Starting server on port : " + IpAddress + ":" + port);
     NetworkComms.AppendGlobalConnectionEstablishHandler(ClientConnected);
     NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);
     Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Parse(IpAddress), port));
     Console.WriteLine("\nPress q to quit or any other key to continue.");
     while (true)
     {
         if (Console.ReadKey(true).Key == ConsoleKey.Q)
         {
             break;
         }
     }
     NetworkComms.Shutdown();
 }
Example #18
0
        public void Start()
        {
            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions);

            NetworkComms.AppendGlobalIncomingPacketHandler <ProtocolCl>("ReceiveProtocol", PrintIncomingMessage);
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", PrintIncomingMessage);
            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished);
            NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);

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

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

            Console.WriteLine("\nWaiting for games to be launched...");
            while (true)
            {
                lock (games)
                {
                    for (int i = 0; i < games.Count; ++i)
                    {
                        if (games[i].nbPlayers() == 0)
                        {
                            games.RemoveAt(i);
                            i--;
                            continue;
                        }
                        if (games[i].IsFull() && !games[i].IsRunning())
                        {
                            games[i].BeginGame();
                        }
                        if (games[i].IsRunning() && !games[i].IsPlaying())
                        {
                            games[i].PrepareGame();
                        }
                        if (games[i].IsPlaying())
                        {
                            games[i].DoTurn();
                        }
                    }
                }
            }
        }
Example #19
0
        public Tracker()
        {
            this.Peers  = new List <Peer>();
            this.Status = TrackerStatus.Stopped;

            t = new Timer(CommonHelpers.CheckAliveInterval);

            NetworkComms.DisableLogging();
            if (File.Exists("BlockChainVotingsTracker_log.txt"))
            {
                File.Delete("BlockChainVotingsTracker_log.txt");
            }
            LiteLogger logger = new LiteLogger(LiteLogger.LogMode.ConsoleAndLogFile, "BlockChainVotingsTracker_log.txt");

            NetworkComms.EnableLogging(logger);

            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectPeer);
        }
Example #20
0
        public void StartConnection(EClientType type)
        {
            DiscoverPeersTimer.AutoReset = true;
            DiscoverPeersTimer.Interval  = 1000;
            DiscoverPeersTimer.Elapsed  += DiscoverPeersTimer_Elapsed;
            DiscoverPeersTimer.Start();

            ClientId = new ClientIdData(Environment.MachineName, CommonDebug.GetOptionalNumberId(), type);

            PeerDiscovery.EnableDiscoverable(PeerDiscovery.DiscoveryMethod.UDPBroadcast);

            PeerDiscovery.OnPeerDiscovered += PeerDiscovery_OnPeerDiscovered;

            PeerDiscovery.DiscoverPeersAsync(PeerDiscovery.DiscoveryMethod.UDPBroadcast);

            NetworkComms.AppendGlobalConnectionEstablishHandler(conn => OnConnectionEstablished(conn));
            NetworkComms.AppendGlobalConnectionCloseHandler(conn => OnConnectionClosed(conn));
        }
        private static void SetupGlobalNetworkHandler(GlobalRegister gamecontext)
        {
            #region Global Handler

            NetworkComms.AppendGlobalConnectionEstablishHandler(connection => { TStuffLog.Debug("Icomming connection"); });
            NetworkComms.AppendGlobalConnectionCloseHandler(connection =>
            {
                gamecontext.GameSessions.LeaveGame(connection);
                gamecontext.User.RemoveUser(connection);
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <EchoObject>("echo", (header, connection, incomingObject) =>
            {
                TStuffLog.Debug("Echo Object");
                TStuffLog.Debug($"Object info {incomingObject.Id} - {incomingObject.Message}");
                connection.SendObject("echo", incomingObject);
            });

            #endregion
        }
Example #22
0
        private void ConfigGlobalConnectionHandler()
        {
            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleConnectionEstablish);

            //send self client info
            NetworkComms.AppendGlobalIncomingPacketHandler <ClientInfo>(PacketType.REQ_ClientInfo, HandleClientInfo);

            //request online client infos
            NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketType.REQ_OnlineClientInfos, HandleOnlineClientInfos);

            //request NAT info
            NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketType.REQ_NATInfo, HandleNATInfo);

            //request NAT info
            NetworkComms.AppendGlobalIncomingPacketHandler <P2PRequest>(PacketType.REQ_UDPP2PRequest, HandleUDPP2PRequest);

            //feedback established p2p connection with specified client
            NetworkComms.AppendGlobalIncomingPacketHandler <P2PRequest>(PacketType.REQ_P2PEstablished, HandleP2PEstablished);

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClose);
        }
Example #23
0
        /// <summary>
        /// constructor of the server
        /// </summary>
        public NCServer()
        {
            // setup the communication
            customSendReceiveOptions = new SendReceiveOptions <ProtobufSerializer>();
            ConnectionInfo serverConnectionInfo = new ConnectionInfo(new IPEndPoint(IPAddress.Any, PortServer)); // TODO: check if this line has any utility

            //Start listening for incoming TCP connections
            if (!serverEnabled)
            {
                EnableServer_Toggle();
            }


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

            // if a client disconnects
            NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);

            // if a client connects
            NetworkComms.AppendGlobalConnectionEstablishHandler(ClientConnected);

            // if an update is received
            NetworkComms.AppendGlobalIncomingPacketHandler <CommunicateUpdate>("Update", (header, connection, message) =>
            {
                string content = message.Message;

                OnGetSelected(this, new Event(content)); // calls myNCServer.OnGetSelected += new NCServer.EventHandler(UpdateRichTextBox); in Form1
                //RichTextBox1.Text = content; // you can't update from this thread
            });

            // if we press that key, the server can receive it
            NetworkComms.AppendGlobalIncomingPacketHandler <int>("SecondaryIndexTrigger", (header, connection, message) =>
            {
                Console.WriteLine("SecondaryIndexTrigger");
                SendMyObject(); // here we ask for the creation of an object
            });
        }
Example #24
0
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler <Message>("CardGame", HandleGame, customSendReceiveOptions);
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Chat", HandleChat, customSendReceiveOptions);
            NetworkComms.AppendGlobalConnectionEstablishHandler(HandleNewConnection);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleDisconnection);

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

            ShowConnect();
            read_line();

            NetworkComms.Shutdown();
            //   NetworkComms.AppendGlobalIncomingPacketHandler<string>("message", PrintIncomingMessage);
            // Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));
            // System.Console.WriteLine("Server listening for TCP connection on:");
            // foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            //     System.Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            // System.Console.WriteLine("\nPress any key to close the server.");
            // System.Console.ReadKey();
            // NetworkComms.Shutdown();
        }
Example #25
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);
        }
Example #26
0
        public static bool StartServer(int Port, string Password)
        {
            try
            {
                _Password = Password;
                logger.Info("Starting Server");

                NetworkComms.AppendGlobalConnectionEstablishHandler(HandleNewConnection, false);
                NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
                NetworkComms.AppendGlobalIncomingPacketHandler <iRTVOMessage>("iRTVOMessage", HandleIncomingMessage);

                NetworkComms.DefaultListenPort = Port;
                TCPConnection.StartListening(false);
                isAuthenticated[NetworkComms.NetworkIdentifier] = true; // Server is always authenticated!
            }
            catch (CommsSetupShutdownException ex)
            {
                logger.Error("Failed to start Server: {0}", ex.Message);

                return(false);
            }
            isServer = true;
            return(true);
        }
Example #27
0
        internal static void Start()
        {
            connections.Clear();
            pendingConnections.Clear();
            connectionDictionary.Clear();
            encryptionKeys.Clear();

            StringReader  stringReader = new StringReader(Properties.Resources.privkey);
            XmlSerializer serializer   = new XmlSerializer(typeof(RSAParameters));

            rsaParams = (RSAParameters)serializer.Deserialize(stringReader);
            NetworkComms.AppendGlobalConnectionEstablishHandler((connection) =>
            {
                pendingConnections.Add(connection.ConnectionInfo.NetworkIdentifier.Value);
            });
            NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>("Handshake", (header, connection, bytes) =>
            {
                byte[] publicBlob;
                using (MemoryStream readStream = new MemoryStream(bytes))
                {
                    using (BinaryReader reader = new BinaryReader(readStream))
                    {
                        ushort blobSize = reader.ReadUInt16();
                        publicBlob      = reader.ReadBytes(blobSize);
                    }
                }
                if (pendingConnections.Contains(connection.ConnectionInfo.NetworkIdentifier.Value))
                {
                    pendingConnections.Remove(connection.ConnectionInfo.NetworkIdentifier.Value);
                    using (ECDiffieHellmanCng diffieHellman = new ECDiffieHellmanCng())
                    {
                        byte[] salt = new byte[8];
                        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                        {
                            rng.GetBytes(salt);
                        }
                        using (Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(diffieHellman.DeriveKeyMaterial(CngKey.Import(publicBlob, CngKeyBlobFormat.EccPublicBlob)), salt, 1000))
                        {
                            encryptionKeys.Add(connection.ConnectionInfo.NetworkIdentifier.Value, deriveBytes.GetBytes(32));
                        }
                        using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                        {
                            try
                            {
                                csp.ImportParameters(rsaParams);
                                byte[] serverPublicPart = diffieHellman.PublicKey.ToByteArray();
                                byte[] signature        = csp.SignData(serverPublicPart, new SHA512CryptoServiceProvider());
                                using (MemoryStream sendStream = new MemoryStream(salt.Length + serverPublicPart.Length + signature.Length + 6))
                                {
                                    using (BinaryWriter writer = new BinaryWriter(sendStream))
                                    {
                                        writer.Write((ushort)salt.Length);
                                        writer.Write(salt);
                                        writer.Write((ushort)serverPublicPart.Length);
                                        writer.Write(serverPublicPart);
                                        writer.Write((ushort)signature.Length);
                                        writer.Write(signature);
                                    }
                                    connection.SendObject("HandshakeResponse", sendStream.GetBuffer());
                                    connections.Add(connection);
                                    connectionDictionary.Add(connection.ConnectionInfo.NetworkIdentifier.Value, connection);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                            finally
                            {
                                csp.PersistKeyInCsp = false;
                            }
                        }
                    }
                }
                else
                {
                    //Something wrong. Disconnect them.
                    connection.CloseConnection(true);
                }
            });
            NetworkComms.AppendGlobalConnectionCloseHandler((connection) =>
            {
                if (connectionDictionary.ContainsKey(connection.ConnectionInfo.NetworkIdentifier.Value))
                {
                    connectionDictionary.Remove(connection.ConnectionInfo.NetworkIdentifier.Value);
                    connections.RemoveAll(x => x.ConnectionInfo.NetworkIdentifier.Value == connection.ConnectionInfo.NetworkIdentifier.Value);
                    encryptionKeys.Remove(connection.ConnectionInfo.NetworkIdentifier.Value);
                }
            });
            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, Config.LISTEN_PORT));
        }
Example #28
0
 private static void RegisterOnConnectHandler()
 {
     NetworkComms.AppendGlobalConnectionEstablishHandler((connection) => {
         onConnect(connection);
     });
 }
        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);
        }
Example #30
0
        public static void Bind()
        {
            Net.Init();
            NetworkComms.AppendGlobalConnectionEstablishHandler((connection) =>
            {
                // todo: Automatically disconnect after 60 seconds without a handshake
            });

            NetworkComms.AppendGlobalConnectionCloseHandler((connection) =>
            {
                DisconnectPlayer(connection.GetID());
            });


            Net.On <C2S_Handshake>((header, connection, obj) =>
            {
                var response = new S2C_HandshakeResponse(obj.Version == VERSION, IsNicknameValid(obj.Nickname), "OK", null);
                if (IsValidPlayer(connection.GetID()))
                {
                    //handshake for second time.. let's disconnect
                    DisconnectPlayer(connection.GetID());
                }
                if (!response.OK)
                {
                    response.Message = $"Error:\n Version: {response.VersionOK}\n Nickname: {response.NicknameOK}";
                    if (!response.NicknameOK)
                    {
                        response.Message += "\n Nickname length must be within 3-16 characters and MUST be unique.";
                    }
                }
                else
                {
                    // OK!
                    var player = new RemotePlayer()
                    {
                        Connection = connection, Nickname = obj.Nickname, PlayerState = PlayerState.HANDSHAKE_OK
                    };
                    response.LocalPlayer = player.GetDisplay();
                    AddPlayer(player);
                }
                connection.Send(response);
            });

            Net.On <C2S_JoinLobby>((header, connection, obj) =>
            {
                RemotePlayer player;
                if (IsValidPlayer(connection.GetID(), out player))
                {
                    LobbyServer.EnterLobby(player);
                }
            });

            Net.On <C2S_SendPlayerInvite>((header, connection, obj) =>
            {
                RemotePlayer source, destination;
                if (IsValidPlayer(connection.GetID(), out source, PlayerState.IN_LOBBY) &&
                    IsValidPlayer(obj.Destination, out destination, PlayerState.IN_LOBBY))
                {
                    source.SendInvite(destination);
                }
            });

            Net.On <C2S_RevokeSentPlayerInvite>((header, connection, obj) =>
            {
                RemotePlayer source, destination;
                if (IsValidPlayer(connection.GetID(), out source, PlayerState.IN_LOBBY) &&
                    IsValidPlayer(obj.Destination, out destination, PlayerState.IN_LOBBY))
                {
                    source.RevokeSentInvite(destination);
                }
            });

            Net.On <C2S_AcceptIncomingPlayerInvite>((header, connection, obj) =>
            {
                RemotePlayer source, destination;
                if (IsValidPlayer(obj.Source, out source, PlayerState.IN_LOBBY) &&
                    IsValidPlayer(connection.GetID(), out destination, PlayerState.IN_LOBBY))
                {
                    if (source.HasSentInviteTo(destination))
                    {
                        //We have a pair :)
                        LobbyServer.LeaveLobby(source);
                        LobbyServer.LeaveLobby(destination);
                        GameServer.InitNewGame(source, destination);
                    }
                }
            });

            Net.On <C2S_GameReady>((header, connection, obj) =>
            {
                RemotePlayer player;
                if (IsValidPlayer(connection.GetID(), out player, PlayerState.IN_GAME))
                {
                    var p = player.Game.GetPlayer(player);
                    player.Game.OnPlayerReady(p);
                }
            });

            Net.On <C2S_FireAt>((header, connection, obj) =>
            {
                RemotePlayer player;
                if (IsValidPlayer(connection.GetID(), out player, PlayerState.IN_GAME))
                {
                    var p = player.Game.GetPlayer(player);
                    p.FireAtEnemy(obj.X, obj.Y);
                }
            });
        }