public override bool IsSharable => true;//标注一个channel handler可以被多个channel安全地共享。

        /// <summary>
        /// 收到服务端回应消息
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            try
            {
                TestEvent testEvent = MessagePackSerializer.Deserialize <TestEvent>(MessagePackSerializer.Serialize(msg));
                if (testEvent.code == EventCode.Ping)
                {
                    lstSendPings.Clear();
                    RecordLogEvent?.Invoke("收到Android端心跳回应");
                    return;
                }
                else if (testEvent.code == EventCode.OK)
                {
                    lock (lockOjb)
                    {
                        lstNeedSendDatas.RemoveAll(cu => cu.TestEvent.reqId == testEvent.reqId);
                    }
                }
                else if (testEvent.code == EventCode.Chat)
                {
                    ReceiveEventFromClientEvent?.Invoke(testEvent);
                }
                var eventMsg = JsonConvert.SerializeObject(testEvent);
                RecordLogEvent?.Invoke($"收到Android端消息:{eventMsg}");
            }
            catch (Exception ex)
            {
                RecordLogEvent?.Invoke($"读取数据异常:{ex.Message}");
            }
        }
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     Reconnect(context);
     base.ChannelInactive(context);
     RecordLogEvent?.Invoke("Client ChannelInactive:" + context);
     isConnect = false;
 }
Пример #3
0
        protected virtual void DoWriteLine()
        {
            bool isError = false;

            do
            {
                isError = false;
                try
                {
                    if (!Directory.Exists(LogDirect))
                    {
                        Directory.CreateDirectory(LogDirect);
                    }
                    using (StreamWriter fileStream = new StreamWriter(FilePath, true))
                    {
                        Thread.Sleep(500);
                        do
                        {
                            if (!m_logList.IsEmpty && m_logList.TryDequeue(out LogInfo logInfo))
                            {
                                RecordLogEvent?.Invoke(fileStream, logInfo);
                            }
                        } while (m_logList.Count > 0);
                    }
                }
                catch
                {
                    isError = true;
                    Thread.Sleep(2000);
                }
            } while (isError);
            m_curTask = null;
        }
 /// <summary>
 /// 发送数据
 /// </summary>
 private void SendData()
 {
     if (isRunning)
     {
         return;
     }
     isRunning = true;
     ThreadPool.QueueUserWorkItem(sen =>
     {
         while (true)
         {
             try
             {
                 TestEventCount sendEvent = null;
                 lock (lockOjb)
                 {
                     sendEvent = lstNeedSendDatas.FirstOrDefault(cu => cu.TryCount < TestEventCount.MAX_TRY_COUNT);
                 }
                 if (sendEvent != null)
                 {
                     channelHandlerContext.WriteAndFlushAsync(sendEvent.TestEvent);
                     RecordLogEvent?.Invoke($"发送到服务端:{JsonConvert.SerializeObject(sendEvent.TestEvent)}");
                     sendEvent.TryCount++;
                 }
             }
             catch (Exception ex2)
             {
                 RecordLogEvent?.Invoke($"发送到服务端异常:{ex2.Message}");
             }
             Thread.Sleep(TimeSpan.FromSeconds(0.5));
         }
     });
 }
        /// <summary>
        /// 读写超时通知
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="evt"></param>
        public override void UserEventTriggered(IChannelHandlerContext ctx, object evt)
        {
            if (!(evt is IdleStateEvent))
            {
                return;
            }

            // 发送的ping,超过一定范围,认为与服务端断开连接,需要重连
            if (lstSendPings.Count >= MAX_NO_RESPONSE_PING_COUNT)
            {
                ctx.CloseAsync();
                return;
            }

            // 向服务端发送心跳
            var testEvent = new TestEvent()
            {
                code  = EventCode.Ping,
                reqId = Guid.NewGuid().ToString()
            };

            lstSendPings.Add(testEvent);
            ctx.WriteAndFlushAsync(testEvent);
            RecordLogEvent?.Invoke("发送心跳");
        }
Пример #6
0
        public override bool IsSharable => true;//标注一个channel handler可以被多个channel安全地共享。

        /// <summary>
        /// 收到客户端回应
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            channelHandlerContext = ctx;
            try
            {
                NettyBody testEvent = MessagePackSerializer.Deserialize <NettyBody>(MessagePackSerializer.Serialize(msg));

                // 服务端收到心跳,直接回应
                if (testEvent.code == (int)NettyCodeEnum.Ping)
                {
                    ctx.WriteAndFlushAsync(msg);
                    RecordLogEvent?.Invoke(true, $"收到心跳并原文回应:{ctx.Channel.RemoteAddress}");
                    return;
                }
                if (testEvent.code == (int)NettyCodeEnum.Chat)
                {
                    RecordLogEvent?.Invoke(true, $"服务端接收到聊天消息({ctx.Channel.RemoteAddress}):" + JsonConvert.SerializeObject(testEvent));

                    // 回应收到消息成功
                    testEvent.code = (int)NettyCodeEnum.OK;
                    ctx.WriteAndFlushAsync(testEvent);
                    ReceiveEventFromClientEvent?.Invoke(testEvent);
                    return;
                }
                RecordLogEvent?.Invoke(true, $"服务端接收到消息({ctx.Channel.RemoteAddress}):" + JsonConvert.SerializeObject(testEvent));
            }
            catch (Exception ex)
            {
                RecordLogEvent?.Invoke(false, $"收到客户端消息,处理失败({ctx.Channel.RemoteAddress}):{ex.Message}");
            }
        }
Пример #7
0
        public override bool IsSharable => true;//标注一个channel handler可以被多个channel安全地共享。

        /// <summary>
        /// 收到客户端回应
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            try
            {
                TestEvent testEvent = MessagePackSerializer.Deserialize <TestEvent>(MessagePackSerializer.Serialize(msg));

                // 服务端收到心跳,直接回应
                if (testEvent.code == EventCode.Ping)
                {
                    ctx.WriteAndFlushAsync(msg);
                    RecordLogEvent?.Invoke($"收到心跳并原文回应");
                    return;
                }
                else if (testEvent.code == EventCode.Chat)
                {
                    // 回应收到消息成功
                    testEvent.code = EventCode.OK;
                    ctx.WriteAndFlushAsync(testEvent);
                    ReceiveEventFromClientEvent?.Invoke(testEvent);
                }
                RecordLogEvent?.Invoke($"服务端接收到消息:" + JsonConvert.SerializeObject(testEvent));
            }
            catch (Exception ex)
            {
                RecordLogEvent?.Invoke($"收到客户端消息,处理失败:{ex.Message}");
            }
        }
Пример #8
0
 //服务器监听到客户端活动时
 public override void ChannelActive(IChannelHandlerContext context)
 {
     channelHandlerContext = context;
     RecordLogEvent?.Invoke($"客户端{context.Channel.RemoteAddress}在线.");
     //SimpleEventBus.GetDefaultEventBus().Post("在线:" + context, TimeSpan.Zero);
     base.ChannelActive(context);
 }
 /// <summary>
 /// 通道激活
 /// </summary>
 /// <param name="context"></param>
 public override void ChannelActive(IChannelHandlerContext context)
 {
     var clientAddress = context.Channel.RemoteAddress.ToString();
     dictClients[clientAddress] = context;
     ReceiveClientOnlineEvent?.Invoke(clientAddress);
     RecordLogEvent?.Invoke(true, $"客户端上线:{context.Channel.RemoteAddress}");
     RecordLogEvent?.Invoke(true, $"通道激活:{context.Channel.RemoteAddress}");
     base.ChannelActive(context);
 }
Пример #10
0
        //客户端下线断线时
        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            RecordLogEvent?.Invoke($"客户端{context}下线.");
            base.HandlerRemoved(context);

            groups.Remove(context.Channel);
            //groups.WriteAndFlushAsync($"恭送{context.Channel.RemoteAddress}离开.");
            //SimpleEventBus.GetDefaultEventBus().Post("下线:" + context, TimeSpan.Zero);
        }
Пример #11
0
 /// <summary>
 /// 发送数据到客户端
 /// </summary>
 /// <param name="testEvent"></param>
 public void SendData(NettyBody testEvent)
 {
     try
     {
         if (channelHandlerContext == null)
         {
             RecordLogEvent?.Invoke(false, $"未连接客户端,无法发送数据");
             return;
         }
         channelHandlerContext.WriteAndFlushAsync(testEvent);
     }
     catch (Exception ex)
     {
         RecordLogEvent?.Invoke(false, $"发送数据异常:{ex.Message}");
     }
 }
Пример #12
0
        protected virtual void DoWriteLine()
        {
            bool isError = false;

            do
            {
                isError = false;
                try
                {
                    if (!Directory.Exists(LogDirect))
                    {
                        Directory.CreateDirectory(LogDirect);
                    }
                    using (StreamWriter fileStream = new StreamWriter(FilePath, true))
                    {
                        Thread.Sleep(500);
                        do
                        {
                            if (!m_logList.IsEmpty)
                            {
                                LogInfo logInfo = null;
                                if (m_logList.TryDequeue(out logInfo))
                                {
                                    try
                                    {
                                        RecordLogEvent?.Invoke(fileStream, logInfo);
                                    }
                                    catch (Exception ex)
                                    {
                                        fileStream.WriteLine($"文件写入失败:{Environment.NewLine}{ex.Message}");
                                    }
                                }
                            }
                        } while (m_logList.Count > 0);
                    }
                }
                catch
                {
                    isError = true;
                    Thread.Sleep(2000);
                }
            } while (isError);
            m_curTask = null;
        }
Пример #13
0
 public override void UserEventTriggered(IChannelHandlerContext context, object evt)
 {
     RecordLogEvent?.Invoke($"已经15秒未收到客户端的消息了!");
     if (evt is IdleStateEvent eventState)
     {
         if (eventState.State == IdleState.ReaderIdle)
         {
             lossConnectCount++;
             if (lossConnectCount > 2)
             {
                 RecordLogEvent?.Invoke($"关闭这个不活跃通道!");
                 context.CloseAsync();
             }
         }
     }
     else
     {
         base.UserEventTriggered(context, evt);
     }
 }
        public override bool IsSharable => true;//标注一个channel handler可以被多个channel安全地共享。

        /// <summary>
        /// 收到客户端回应
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        protected override void ChannelRead0(IChannelHandlerContext ctx, ChatInfo msg)
        {
            try
            {
                // 服务端收到心跳,直接回应
                if (msg.Code == (int)NettyCodeEnum.Ping)
                {
                    ctx.WriteAndFlushAsync(msg);
                    RecordLogEvent?.Invoke(true, $"收到心跳并原文回应:{ctx.Channel.RemoteAddress}");
                    return;
                }
                if (msg.Code == (int)NettyCodeEnum.Chat)
                {
                    RecordLogEvent?.Invoke(true, $"服务端接收到聊天消息({ctx.Channel.RemoteAddress}):" + JsonConvert.SerializeObject(msg));

                    foreach (var kvp in dictClients)
                    {
                        if (ctx.Channel.RemoteAddress.ToString() == kvp.Key)
                        {
                            // 回应收到消息成功
                            msg.Code = (int)NettyCodeEnum.OK;
                        }
                        else
                        {
                            // 群发消息
                            msg.Code = (int)NettyCodeEnum.Chat;
                        }
                        kvp.Value.WriteAndFlushAsync(msg);
                    }
                    msg.FromId = ctx.Channel.RemoteAddress.ToString();
                    ReceiveEventFromClientEvent?.Invoke(msg);
                    return;
                }
                RecordLogEvent?.Invoke(true, $"服务端接收到消息({ctx.Channel.RemoteAddress}):" + JsonConvert.SerializeObject(msg));

            }
            catch (Exception ex)
            {
                RecordLogEvent?.Invoke(false, $"收到客户端消息,处理失败({ctx.Channel.RemoteAddress}):{ex.Message}");
            }
        }
 /// <summary>
 /// 发送数据到客户端
 /// </summary>
 /// <param name="testEvent"></param>
 public void SendData(ChatInfo testEvent)
 {
     try
     {
         if (dictClients == null || dictClients.Count <= 0)
         {
             RecordLogEvent?.Invoke(false, $"未连接客户端,无法发送数据");
             return;
         }
         foreach (var kvp in dictClients)
         {
             RecordLogEvent?.Invoke(true, $"向客户端({kvp.Key})发送消息:{testEvent.Data}");
             testEvent.ToId = kvp.Key;
             kvp.Value.WriteAndFlushAsync(testEvent);
         }
     }
     catch (Exception ex)
     {
         RecordLogEvent?.Invoke(false, $"发送数据异常:{ex.Message}");
     }
 }
Пример #16
0
 protected virtual void DoWriteLine()
 {
     bool isError = false;
     do {
         isError = false;
         try
         {
             do
             {
                 StreamWriter fileStream = new StreamWriter(FilePath, true);
                 do
                 {
                     if (!m_logList.IsEmpty)
                     {
                         LogInfo logInfo = null;
                         if (m_logList.TryDequeue(out logInfo))
                         {
                             try
                             {
                                 RecordLogEvent?.Invoke(fileStream, logInfo);
                             }
                             catch
                             {
                             }
                         }
                     }
                 } while (m_logList.Count > 0);
                 Thread.Sleep(1000);
                 fileStream.Close();
             } while (m_logList.Count > 0);
         }
         catch
         {
             isError = true;
             Thread.Sleep(2000);
         }
     } while (isError);
     m_curTask = null;
 }
Пример #17
0
        //客户端连接进来时
        public override void HandlerAdded(IChannelHandlerContext context)
        {
            RecordLogEvent?.Invoke($"客户端{context}上线.");
            //SimpleEventBus.GetDefaultEventBus().Post("客户端连接进来:" + context, TimeSpan.Zero);
            base.HandlerAdded(context);

            IChannelGroup g = groups;

            if (g == null)
            {
                lock (this)
                {
                    if (groups == null)
                    {
                        g = groups = new DefaultChannelGroup(context.Executor);
                    }
                }
            }

            g.Add(context.Channel);
            //groups.WriteAndFlushAsync($"欢迎{context.Channel.RemoteAddress}加入.");
        }
 /// <summary>
 /// 发送数据到服务端
 /// </summary>
 /// <param name="testEvent"></param>
 public void SendData(TestEvent testEvent)
 {
     try
     {
         lock (lockOjb)
         {
             lstNeedSendDatas.Add(new TestEventCount {
                 TestEvent = testEvent
             });
         }
         if (channelHandlerContext == null)
         {
             RecordLogEvent?.Invoke($"未连接服务,无法发送数据");
             return;
         }
         SendData();
     }
     catch (Exception ex)
     {
         RecordLogEvent?.Invoke($"发送数据异常:{ex.Message}");
     }
 }
        private void SendPing()
        {
            // 发送的ping,超过一定范围,认为与服务端断开连接,需要重连
            if (lstSendPings.Count >= MAX_NO_RESPONSE_PING_COUNT)
            {
                channelHandlerContext.CloseAsync();
                RecordLogEvent?.Invoke($"{lstSendPings.Count} 次未收到心跳回应,重连服务器");
                lstSendPings.Clear();
                Reconnect(channelHandlerContext);
                return;
            }

            // 向服务端发送心跳
            var testEvent = new TestEvent()
            {
                code  = EventCode.Ping,
                reqId = Guid.NewGuid().ToString()
            };

            lstSendPings.Add(testEvent);
            channelHandlerContext.WriteAndFlushAsync(testEvent);
            RecordLogEvent?.Invoke("发送心跳");
        }
 public override void ChannelActive(IChannelHandlerContext context)
 {
     total = 0;
     RecordLogEvent?.Invoke("Client channelActive:" + context);
     isConnect = true;
 }
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     RecordLogEvent?.Invoke(false, $"异常:{exception.Message}");
     context.CloseAsync();
 }
 /// <summary>
 /// 注销通道
 /// </summary>
 /// <param name="context"></param>
 public override void ChannelUnregistered(IChannelHandlerContext context)
 {
     base.ChannelUnregistered(context);
     RecordLogEvent?.Invoke(false, $"注销通道:{context.Channel.RemoteAddress}");
 }
 /// <summary>
 /// 断开连接
 /// </summary>
 /// <param name="context"></param>
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     RecordLogEvent?.Invoke(false, $"断开连接:{context.Channel.RemoteAddress}");
     base.ChannelInactive(context);
 }
 /// <summary>
 /// 消息读取完成
 /// </summary>
 /// <param name="context"></param>
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     base.ChannelReadComplete(context);
     context.Flush();
     RecordLogEvent?.Invoke(true, $"ChannelReadComplete");
 }
 public override void HandlerRemoved(IChannelHandlerContext context)
 {
     Reconnect(context);
     RecordLogEvent?.Invoke($"服务端{context}下线.");
     base.HandlerRemoved(context);
 }
Пример #26
0
 /// <summary>
 /// 通道激活
 /// </summary>
 /// <param name="context"></param>
 public override void ChannelActive(IChannelHandlerContext context)
 {
     channelHandlerContext = context;
     RecordLogEvent?.Invoke(true, $"通道激活:{context.Channel.RemoteAddress}");
     base.ChannelActive(context);
 }
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     RecordLogEvent?.Invoke("Exception: " + exception);
     context.CloseAsync();
 }
 public override void ChannelUnregistered(IChannelHandlerContext context)
 {
     base.ChannelUnregistered(context);
     Reconnect(context);
     RecordLogEvent?.Invoke("Client ChannelUnregistered:" + context);
 }
 public override void HandlerAdded(IChannelHandlerContext context)
 {
     this.channelHandlerContext = context;
     RecordLogEvent?.Invoke($"HandlerAdded.");
     base.HandlerAdded(context);
 }
 public override void HandlerRemoved(IChannelHandlerContext context)
 {
     RecordLogEvent?.Invoke($"HandlerRemoved");
     base.HandlerRemoved(context);
 }