123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using DotNetty.Transport.Channels;
- using System;
- using System.Collections.Concurrent;
- using System.Windows.Forms;
- using Message = Cn.Sagacloud.Proto.Message;
- namespace NettyClient
- {
- public class SimpleMessageHandler : ChannelHandlerAdapter
- {
- public SimpleMessageHandler()
- {
- //var protobufEncoder = new ProtobufEncoder();
- }
- public static ConcurrentQueue<Message> messageQueue = new ConcurrentQueue<Message>();
- public IChannelHandlerContext context;
- public override void ChannelActive(IChannelHandlerContext context)
- {
- //MessageBox.Show("connected");
- TaskNettyClient.isConnected = true;
- this.context = context;
- }
- public override void ChannelRead(IChannelHandlerContext context, object message)
- {
- if (message is Message msg)
- {
- toString(msg);
- messageQueue.Enqueue(msg);
- }
- }
- public override void ChannelReadComplete(IChannelHandlerContext context)
- {
- context.Flush();
- }
- public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
- {
- Console.WriteLine("Exception: " + exception);
- context.CloseAsync();
- }
- public override void ChannelInactive(IChannelHandlerContext context)
- {
- base.ChannelInactive(context);
- Console.WriteLine("1");
- TaskNettyClient.isConnected = false;
- }
- public override void ChannelUnregistered(IChannelHandlerContext context)
- {
- base.ChannelUnregistered(context);
- Console.WriteLine("2");
- }
- public override void HandlerRemoved(IChannelHandlerContext context)
- {
- base.HandlerRemoved(context);
- }
- public void toString(Message msg)
- {
- Console.WriteLine("Received from server: cmd : " + msg.Cmd + ", taskId : " + msg.TaskId + ", content : " + msg.Content);
- }
- public bool WriteMessage(Message message)
- {
- if (context == null || !context.Channel.Active)
- {
- return false;
- }
- try
- {
- context.WriteAndFlushAsync(message);
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
- }
|