Exemplo n.º 1
0
        public RabbitMQMessagePublisher(
            ILoggerFactory loggerFactory,
            TaskFactory taskFactory,
            IMessagePacker messagePacker,
            IConnectionFactory connectionFactory)
        {
            _taskFactory   = taskFactory;
            _messagePacker = messagePacker;
            _loggerFactory = loggerFactory;
            _connection    = _connection = new Lazy <IConnection>(() =>
            {
                var logger = _loggerFactory.CreateLogger <RabbitMQMessagePublisher>();

                var tryCount = 0;
                var timeOut  = TimeSpan.FromSeconds(4);

                while (tryCount != 20)
                {
                    Interlocked.Increment(ref tryCount);
                    try
                    {
                        var connection = connectionFactory.CreateConnection(Assembly.GetEntryAssembly().FullName);
                        logger.LogInformation("Connection is succesfull => {connection}", connection);
                        return(connection);
                    }
                    catch (BrokerUnreachableException e)
                    {
                        logger.LogError("Can't connect to the RabbitMq bus. Trying to reconnect in {timeOut} | Try[{tryCount}]. Exception {e}", timeOut, tryCount, e);
                        Task.Delay(timeOut).GetAwaiter().GetResult();
                    }
                }
                throw new Exception("No connection to the event bus");
            });
            _publishChannel = new Lazy <IModel>(() => _connection.Value.CreateModel());
        }
Exemplo n.º 2
0
        //accept(address i.e. 127.0.0.1:10002)
        public BaseNetwork(NetworkProtocol protocol, string address, IMessagePacker msgPacker, int packetSize = Packet.PacketSizeLength4)
        {
            _msgPacker = msgPacker;
            _sessions  = new Dictionary <long, NetworkSession>();
            try
            {
                IPEndPoint ipEndPoint;
                switch (protocol)
                {
                case NetworkProtocol.TCP:
                    ipEndPoint = NetworkHelper.ToIPEndPoint(address);
                    _service   = new TService(packetSize, ipEndPoint, channel => { OnAccept(channel); });
                    break;

                case NetworkProtocol.WebSocket:
                    var prefixes = address.Split(';');
                    _service = new WService(prefixes, channel => { OnAccept(channel); });
                    break;
                }
            }
            catch (Exception e)
            {
                throw new Exception($"NetworkComponent Awake Error {address}", e);
            }
        }
 protected CapPublisherBase(IServiceProvider service)
 {
     ServiceProvider = service;
     _transaction    = service.GetRequiredService <CapTransactionBase>();
     _msgPacker      = service.GetRequiredService <IMessagePacker>();
     _serializer     = service.GetRequiredService <IContentSerializer>();
 }
Exemplo n.º 4
0
 public Session(NetworkComponent network, AChannel channel, IMessagePacker messagePacker)
 {
     this.network       = network;
     this.channel       = channel;
     this.messagePacker = messagePacker;
     this.StartRecv();
 }
Exemplo n.º 5
0
 protected CapPublisherBase(IServiceProvider service)
 {
     ServiceProvider = service;
     _dispatcher     = service.GetRequiredService <IDispatcher>();
     _msgPacker      = service.GetRequiredService <IMessagePacker>();
     _serializer     = service.GetRequiredService <IContentSerializer>();
     Transaction     = new AsyncLocal <ICapTransaction>();
 }
Exemplo n.º 6
0
 public DefaultConsumerInvoker(ILoggerFactory loggerFactory,
                               IServiceProvider serviceProvider,
                               IMessagePacker messagePacker,
                               IModelBinderFactory modelBinderFactory)
 {
     _modelBinderFactory = modelBinderFactory;
     _serviceProvider    = serviceProvider;
     _messagePacker      = messagePacker;
     _logger             = loggerFactory.CreateLogger <DefaultConsumerInvoker>();
 }
 public CallbackMessageSender(
     ILogger <CallbackMessageSender> logger,
     IServiceProvider serviceProvider,
     IContentSerializer contentSerializer,
     IMessagePacker messagePacker)
 {
     _logger            = logger;
     _serviceProvider   = serviceProvider;
     _contentSerializer = contentSerializer;
     _messagePacker     = messagePacker;
 }
Exemplo n.º 8
0
 public ConsumerInvokerFactory(
     ILoggerFactory loggerFactory,
     IMessagePacker messagePacker,
     IModelBinderFactory modelBinderFactory,
     IServiceProvider serviceProvider)
 {
     _loggerFactory      = loggerFactory;
     _messagePacker      = messagePacker;
     _modelBinderFactory = modelBinderFactory;
     _serviceProvider    = serviceProvider;
 }
Exemplo n.º 9
0
        /// <summary>
        /// 服务器初始化 配置文件初始化、协议字典初始化、网络初始化
        /// </summary>
        /// <typeparam name="GlobalConfigureType"></typeparam>
        /// <param name="globalPath"></param>
        /// <param name="plyaerContextType"></param>
        /// <param name="messageDispather"></param>
        /// <param name="opcodeTypeDictionary"></param>
        /// <param name="messagePraser"></param>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public virtual bool Initialize <GlobalConfigureType, PlayerContextBase>(string globalPath, Type plyaerContextType, IMessagePacker messagePraser, string serverName
                                                                                )
            where GlobalConfigureType : ServerBaseGlobalConfigure, new()
            where PlayerContextBase : class
        {
            if (!InitlizeLogConfigure())
            {
                Log.Error("初始化日志系统失败");
                return(false);
            }

            //默认为protobufPraser
            m_messagePraser = messagePraser;

            //初始化配置文件
            if (!InitlizeServerConfigure <GlobalConfigureType>(globalPath, serverName))
            {
                Log.Error("初始化配置文件失败");
                return(false);
            }
            //初始化上下文管理器
            if (!InitializePlayerContextManager(plyaerContextType, m_configServer.maxPlayerCtx))
            {
                Log.Error("初始化玩家上下文管理器失败");
                return(false);
            }
            // 开启timer管理器用于服务器Tick
            Log.Info("ServerBase::Initialization is starting timer manager");
            TimerManager = new TimerManager(PlayerCtxManager);
            if (TimerManager.Start() < 0)
            {
                Log.Error("ServerBase::Initialization started timer manager failed");
                return(false);
            }

            if (!InitlizeObjectFactory())
            {
                Log.Error("对象池初始化失败");
                return(false);
            }

            //初始化网络
            if (!InitializeNetWork())
            {
                Log.Error("配置网络出现错误");
                return(false);
            }

            return(true);
        }
Exemplo n.º 10
0
        //client
        public BaseNetwork(NetworkProtocol protocol, IMessagePacker msgPacker, int packetSize = Packet.PacketSizeLength4)
        {
            _msgPacker = msgPacker;
            _sessions  = new Dictionary <long, NetworkSession>();
            switch (protocol)
            {
            case NetworkProtocol.TCP:
                _service = new TService(packetSize);
                break;

            case NetworkProtocol.WebSocket:
                _service = new WService();
                break;
            }
        }
Exemplo n.º 11
0
        public NetworkSession(long id, BaseNetwork network, BaseChannel channel, IMessagePacker packer, IMessageDispatcher dispatcher)
        {
            Id             = id;
            _network       = network;
            _msgPacker     = packer;
            _msgDispatcher = dispatcher;
            var timeNow = TimeHelper.Now();

            _lastRecvTime    = timeNow;
            _lastSendTime    = timeNow;
            _requestCallback = new Dictionary <int, Action <INetworkMessage> >();

            _channel = channel;
            _channel.ErrorCallback += (c, e) =>
            {
                Log.Info($"session error, sessionId: {Id},  ErrorCode: {e}");
                _network.RemoveSession(id);
            };
            _channel.ReadCallback += OnRead;
        }
        public RabbitMQMessageReceiver(
            IConnectionFactory connectionFactory,
            TaskFactory taskFactory,
            IMessageHandlersRegistry messageHandlersRegistry,
            ILoggerFactory loggerFactory,
            IMessagePacker messagePacker)
        {
            _memoryPipe = new BlockingCollection <HandlingProcessFor <IMessage> >();
            _connection = new Lazy <IConnection>(() =>
            {
                var logger = _loggerFactory.CreateLogger <RabbitMQMessageReceiver>();

                var tryCount = 0;
                var timeOut  = TimeSpan.FromSeconds(4);

                while (tryCount != 20)
                {
                    Interlocked.Increment(ref tryCount);
                    try
                    {
                        var connection = connectionFactory.CreateConnection(Assembly.GetEntryAssembly().FullName);
                        logger.LogTrace("Connection is succesfull => {connection}", connection);
                        return(connection);
                    }
                    catch (BrokerUnreachableException e)
                    {
                        logger.LogError("Can't connect to the RabbitMq bus. Trying to reconnect in {timeOut} | Try[{tryCount}]. Exception {e}", timeOut, tryCount, e);
                        Task.Delay(timeOut).GetAwaiter().GetResult();
                    }
                }
                throw new Exception("No connection to the event bus");
            });

            _taskFactory   = taskFactory;
            _loggerFactory = loggerFactory;
            _messagePacker = messagePacker;

            RegisterAll(messageHandlersRegistry.MessageTypeToDelegateType);
        }
Exemplo n.º 13
0
        public override void Awake(JToken jd = null)
        {
            if (jd == null)
            {
                return;
            }

            if (jd.Parent != null && jd.Parent.Parent != null && jd.Parent.Parent["appType"] != null)
            {
                string[] array = jd.Parent.Parent["appType"].ToString().Replace(" ", "").Split('|');
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] != "")
                    {
                        appType |= (int)Enum.Parse(typeof(AppType), array[i]);
                    }
                }
            }

            protocol = NetworkProtocol.TCP;

            if (jd["protocol"] != null)
            {
                Enum.TryParse <NetworkProtocol>(jd["protocol"].ToString(), out protocol);
            }

            address = jd["address"]?.ToString();
            if (address != null && address != "" && protocol != NetworkProtocol.HttpSocket)
            {
                ipEndPoint = NetworkHelper.ToIPEndPoint(address);
            }
            else
            {
                ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
            }

            if (jd["MessagePacker"]?.ToString() == "ProtobufPacker")
            {
                MessagePacker = new ProtobufPacker();
            }
            else
            {
                MessagePacker = new MongoPacker();
            }

            try
            {
                switch (protocol)
                {
                case NetworkProtocol.KCP:
                    this.Service = new KService(ipEndPoint, this.OnAccept);
                    break;

                case NetworkProtocol.TCP:
                    this.Service = new TService(ipEndPoint, this.OnAccept);
                    break;

                case NetworkProtocol.WebSocket:
                    this.Service = new WService(address.Split(';'), this.OnAccept);
                    break;

                case NetworkProtocol.HttpSocket:
                    string[] prefixs = address.Split(';');
                    Boolean.TryParse(jd["website"]?.ToString(), out bool website);
                    this.Service = new HttpService(prefixs[0], website, this.OnAccept);
                    break;
                }
            }
            catch (Exception e)
            {
                Log.Debug($"创建KService失败!{e.Message}");
                //throw new Exception($"NetworkComponent Awake Error {address}", e);
            }

            ipEndPoint        = this.Service.GetEndPoint();
            IdGenerater.AppId = ipEndPoint.Port;

            if (jd["CheckHearBeat"] != null && this.Service != null)
            {
                this.Service.CheckHearBeat = jd["CheckHearBeat"].ToObject <bool>();
            }

            if (jd["CheckKcpWaitsnd"] != null && this.Service != null)
            {
                this.Service.CheckKcpWaitsnd = jd["CheckKcpWaitsnd"].ToObject <bool>();
            }
        }
Exemplo n.º 14
0
        public override bool Initialize <GlobalConfigureType, PlayerContextBase>(string globalPath, Type plyaerContextType, IMessagePacker messagePraser, string serverName)
        {
            //初始化程序集
            TypeManager.Instance.Add(DLLType.Common, Assembly.GetAssembly(typeof(TypeManager)));
            TypeManager.Instance.Add(DLLType.ServerBase, Assembly.GetAssembly(typeof(ServerBase)));
            TypeManager.Instance.Add(DLLType.GameServer, Assembly.GetAssembly(typeof(FileServer)));

            if (!base.Initialize <GlobalConfigureType, PlayerContextBase>(globalPath, plyaerContextType, messagePraser, serverName))
            {
                return(false);
            }



            return(true);
        }
Exemplo n.º 15
0
        public override bool Initialize <GlobalConfigureType, PlayerContextBase>(string globalPath, Type plyaerContextType, IMessagePacker messagePraser, string serverName)
        {
            //初始化程序集
            TypeManager.Instance.Add(DLLType.Common, Assembly.GetAssembly(typeof(TypeManager)));
            TypeManager.Instance.Add(DLLType.ServerBase, Assembly.GetAssembly(typeof(ServerBase)));
            TypeManager.Instance.Add(DLLType.GameServer, Assembly.GetAssembly(typeof(GameServer)));

            if (!base.Initialize <GlobalConfigureType, PlayerContextBase>(globalPath, plyaerContextType, messagePraser, serverName))
            {
                return(false);
            }
            //获取当前服务器的配置文件
            m_gameServerGlobalConfig = base.m_globalConfigure as global::GameServer.Configure.GameServerGlobalConfig;
            //设置AsyncActionQueuePool
            AsyncActionQueuePool = new SampleGameServerAsyncActionSequenceQueuePool(m_gameServerGlobalConfig.ServerContext.AsyncActionQueueCount);

            //数据库配置
            var dbConfig = m_gameServerGlobalConfig.DBConfigInfos[0];

            //Log.Info($"ip:{dbConfig.ConnectHost} port:{dbConfig.Port} serviceName:{dbConfig.DataBase} username:{dbConfig.UserName} password:{dbConfig.Password}");

            //GCNotification.GCDone += i =>
            //{
            //    Log.Debug("GC = " + i);

            //};
            Log.Debug("GameServer is running with server GC = " + GCSettings.IsServerGC);
            //MongoDBHelper.CreateDBClient(); //测试
            //mongodb测试

            //MongoDBHelper.Test();


            //初始化功能服务的各个模块系统
            if (!InitializeSystem())
            {
                Log.Info("初始化模块系统失败");
                return(false);
            }
            //下面可以写启动逻辑线程 将上述游戏逻辑丢到逻辑线程中处理
            return(true);
        }
Exemplo n.º 16
0
 public override void Start()
 {
     base.Start();
     messagePacker = new ProtobufPacker();
 }