示例#1
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);
        }
示例#2
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;
        }
示例#3
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();
        }
示例#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);
        }
 public ClientNetwork(string ip, int port)
 {
     _serverIp   = ip;
     _serverPort = port;
     NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished);
     NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);
 }
示例#6
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();
        }
示例#7
0
        static void Main(string[] args)
        {
            //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>("ConnectionRequest", ConnectNewUser);
            NetworkComms.AppendGlobalIncomingPacketHandler <string[]>("OpenServer", OpenNewChatServer);
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("connectMe", ConnectToChatServer);
            NetworkComms.AppendGlobalIncomingPacketHandler <string[]>("newMessage", AddMessageChatServer);

            // Close connection and open connection array for new connection
            NetworkComms.AppendGlobalConnectionCloseHandler(closeConnection);
            //Start listening for incoming connections
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));

            //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;
        }
示例#9
0
        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();
        }
示例#10
0
        public void Connect(IPAddress address)
        {
            NetworkComms.RemoveGlobalConnectionCloseHandler(HandleConnectionClosed);

            NetworkComms.Shutdown();

            connectionInfo = new ConnectionInfo(address.ToString(), port);

            if (!packetsAppended)
            {
                NetworkComms.AppendGlobalIncomingPacketHandler <Custom>("Custom", ReceiveCustomPacket);
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PacketName.ReSessionVerificationResult.ToString(), SessionVerificationResultReceived);
                NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketName.ReSessionId.ToString(), SessionIdReceived);
                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.ReUnauthorized.ToString(), UnAuthorizedReceived);

                packetsAppended = true;
            }

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(),
                                                                            NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);
        }
示例#11
0
文件: Program.cs 项目: aneopsy/Powker
        public void Run()
        {
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", PrintIncomingMessage);
            NetworkComms.AppendGlobalIncomingPacketHandler <Protocol>("Protocol", HandleIncomingProtocol);
            NetworkComms.AppendGlobalIncomingPacketHandler <HandShake>("HandShake", HandleIncomingHandShake);
            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
            this.Serializer = DPSManager.GetDataSerializer <ProtobufSerializer>();

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

            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));
            Console.WriteLine("Server listening for TCP connection on:");
            foreach (IPEndPoint l in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", l.Address, l.Port);
            }
            lastServerIPEndPoint = (IPEndPoint)Connection.ExistingLocalListenEndPoints(ConnectionType.TCP).Last();
            while (true)
            {
                if (Clients.Count() == 2)
                {
                    game = new SPoker(Clients.Last(), Clients.First());
                    game.Start();
                }
                Thread.Sleep(200);
            }

            //NetworkComms.Shutdown();
        }
示例#12
0
 public ServiceProxy(string hostname)
 {
     NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectionEstablished, true);
     NetworkComms.AppendGlobalConnectionCloseHandler(OnConnectionClosed);
     NetworkComms.IgnoreUnknownPacketTypes = false;
     // NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions<NetworkingDataContracts.NetworkingDataContractSerializer>();
 }
        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;
        }
示例#14
0
        public Server()
        {
            users = new Dictionary <Connection, ConnectedUser>();

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

            accountManager = new AccountManager();

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

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

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

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

            BroadCastContacts(Config.Properties.BROADCAST_INTERVAL);
        }
示例#15
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);
            }
        }
示例#16
0
 private void AppendListeners()
 {
     NetworkComms.AppendGlobalConnectionCloseHandler(OnServerClose);
     NetworkComms.AppendGlobalIncomingPacketHandler <NetworkPlayer>("Player", OnReceivePlayer);            // low priority
     NetworkComms.AppendGlobalIncomingPacketHandler <NetworkPlayer>("OnConnect", OnConnectedPlayer);       // high priority
     NetworkComms.AppendGlobalIncomingPacketHandler <NetworkCell[]>("OnConnectBlocks", OnConnectedBlocks); // high priority
     NetworkComms.AppendGlobalIncomingPacketHandler <NetworkCell>("CellChanged", OnBlockCellChanged);      // add a high priority on this one
 }
 static SneezeClientListener()
 {
     NetworkComms.AppendGlobalIncomingPacketHandler <string>(Messages.PersonSneezed, HandlePersonSneezed);
     NetworkComms.AppendGlobalIncomingPacketHandler <string>(Messages.UserUpdated, HandleUserUpdated);
     NetworkComms.AppendGlobalIncomingPacketHandler <string>(Messages.SneezeUpdated, HandleSneezeUpdated);
     NetworkComms.AppendGlobalIncomingPacketHandler <string>(Messages.SneezeRemoved, HandleSneezeRemoved);
     NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
 }
 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));
 }
示例#19
0
文件: Server.cs 项目: Sinma1/fTimer
        private void Register()
        {
            NetworkComms.AppendGlobalConnectionCloseHandler(connection =>
            {
                connectedClients.Remove(connection);
            });

            NetworkComms.AppendGlobalIncomingPacketHandler <string>("UpdateMatch", ReceivedUpdateMatch);
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("InitialConnection", ReceiveInitialConnection);

            // MessageBox.Show("ZACZYNAMY SERVER");
        }
示例#20
0
        /// <summary>
        /// Constructor of ServerConnection class.
        /// </summary>
        public ServerConnection()
        {
            // Initialization
            this.Observers            = new List <IObserverWindow>();
            this.Database             = new ServerDatabase();
            this.AuthenticatedClients = new AuthenticatedClients();
            this.ChessGameRoomList    = new ChessGameRoomList();
            this.Logs = string.Empty;

            try
            {
                // Handles connections closing
                NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

                // Handles registration requests
                NetworkComms.AppendGlobalIncomingPacketHandler <ClientCredentials>(PACKET_TYPE_REGISTRATION_REQUEST, HandleRegistrationRequested);

                // Handles login requests
                NetworkComms.AppendGlobalIncomingPacketHandler <ClientCredentials>(PACKET_TYPE_LOGIN_REQUEST, HandleLoginRequested);

                // Handles client's details requests
                NetworkComms.AppendGlobalIncomingPacketHandler <string>(PACKET_TYPE_MYDETAILS_REQUEST, HandleMyDetailsRequested);

                // Handles all clients details requests
                NetworkComms.AppendGlobalIncomingPacketHandler <string>(PACKET_TYPE_ALLCLIENTSDETAILS_REQUEST, HandleAllClientsDetailsRequested);

                // Handles profile modifications requests
                NetworkComms.AppendGlobalIncomingPacketHandler <ClientCredentials>(PACKET_TYPE_MODIFYPROFILE_REQUEST, HandleModifyProfileRequested);

                // Handles gaming room creation requests
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PACKET_TYPE_CREATEROOM_REQUEST, HandleCreateRoomRequested);

                // Handles gaming room joining requests
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PACKET_TYPE_JOINROOM_REQUEST, HandleJoinRoomRequested);

                // Handles gaming room leaving requests
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PACKET_TYPE_LEAVEROOM_REQUEST, HandleLeaveRoomRequested);

                // Handles room informations requests
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PACKET_TYPE_ROOMINFO_REQUEST, HandleRoomInfoRequested);

                // Handles room list requests
                NetworkComms.AppendGlobalIncomingPacketHandler <int>(PACKET_TYPE_ROOMLIST_REQUEST, HandleRoomListRequested);

                // Handles ChessCommands
                NetworkComms.AppendGlobalIncomingPacketHandler <ChessCommand>(PACKET_TYPE_COMMAND_SENT, HandleChessCommandSent);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#21
0
        /// <summary>
        /// Creates <see cref="ServerManager"/>.
        /// </summary>
        public ServerManager()
        {
            IAccountRepository accountRepository = RepositoryFactory.AccountRepository();
            IModuleRepository  moduleRepository  = RepositoryFactory.ModuleRepository();
            IGroupRepository   groupRepository   = RepositoryFactory.GroupRepository();

            accountManager = new AccountManager(accountRepository, groupRepository);
            serviceManager = new ServiceManager(moduleRepository, accountManager);
            moduleManager  = new ModuleManager(accountManager, moduleRepository, serviceManager, groupRepository);

            incomingFileManager = new IncomingFileManager(moduleManager, accountManager);

            NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
        }
示例#22
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();
            }
        }
示例#23
0
文件: Server.cs 项目: Akstasy/coinche
        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);
            }
        }
示例#24
0
 /// <summary>
 /// Server main window constructor
 /// </summary>
 public MainWindow()
 {
     InitializeComponent();
     AppendLineToRichChatBox("Welcome to the Coinche server...");
     localName.Text         = "Server";
     richChatBox.IsReadOnly = true;
     NetworkComms.AppendGlobalIncomingPacketHandler <Message>("Message", HandleIncomingMessage);
     NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
     Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));
     AppendLineToRichChatBox("Listening for incoming TCP connections on:");
     foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
     {
         AppendLineToRichChatBox(listenEndPoint.Address + ":" + listenEndPoint.Port);
     }
 }
        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();
        }
示例#26
0
        public void Start()
        {
            if (!ResolveDns())
            {
                return;
            }

            //_serverConfig.IP = "127.0.0.1";
            ServerMessageReceivedAction("Start connection to Main server");

            try
            {
                _mainConnection = TCPConnection.GetConnection(new ConnectionInfo(_serverConfig.IP, _serverConfig.Port));
                if (_mainConnection.ConnectionInfo.ConnectionState == ConnectionState.Established)
                {
                    _udpTraversal = new UDPTraversal(_serverConfig.IP, _serverConfig.P2P_Port, UDPP2PConnected);

                    //global
                    NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionShutdown);

                    //UDP
                    NetworkComms.AppendGlobalIncomingPacketHandler <string>(PacketType.REQ_P2PMessage, HandleP2PMessage);
                    NetworkComms.AppendGlobalIncomingPacketHandler <Screenshot>(PacketType.REQ_P2PScreenshot, HandleP2PScreenshot);

                    //TCP
                    _mainConnection.AppendIncomingPacketHandler <ClientInfo[]>(PacketType.REQ_OnlineClientInfos, HandleOnlineClientInfos);
                    _mainConnection.AppendIncomingPacketHandler <string>(PacketType.REQ_NATInfo, HandleNATInfo);

                    _mainConnection.AppendIncomingPacketHandler <P2PClient>(PacketType.REQ_UDPP2PRequest, HandleUDPP2PRequest);

                    SendLocalClientInfo();
                }
                else
                {
                    ServerMessageReceivedAction("Failed connect to Main server");

                    NetworkComms.RemoveGlobalConnectionCloseHandler(HandleConnectionShutdown);
                    _mainConnection = null;
                }
            }
            catch (Exception ex)
            {
                ServerMessageReceivedAction("Failed connect to Main server");

                NetworkComms.RemoveGlobalConnectionCloseHandler(HandleConnectionShutdown);
                _mainConnection = null;
            }
        }
示例#27
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();
 }
示例#28
0
        public ServerNetwork(WaitingRoom nroom, int port)
        {
            room = nroom;

            NetworkComms.AppendGlobalIncomingPacketHandler <Hello>("Hello", processHello);
            NetworkComms.AppendGlobalIncomingPacketHandler <Msg>("Msg", processMsg);
            NetworkComms.AppendGlobalIncomingPacketHandler <GameCommand>("GameCommand", processGC);
            NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);

            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

            Console.WriteLine("Listening for messages on:");
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }
        }
示例#29
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();
                        }
                    }
                }
            }
        }
示例#30
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));
        }