SimpleMessageHandler.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using DotNetty.Transport.Channels;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Windows.Forms;
  5. using Message = Cn.Sagacloud.Proto.Message;
  6. namespace NettyClient
  7. {
  8. public class SimpleMessageHandler : ChannelHandlerAdapter
  9. {
  10. public SimpleMessageHandler()
  11. {
  12. //var protobufEncoder = new ProtobufEncoder();
  13. }
  14. public static ConcurrentQueue<Message> messageQueue = new ConcurrentQueue<Message>();
  15. public IChannelHandlerContext context;
  16. public override void ChannelActive(IChannelHandlerContext context)
  17. {
  18. //MessageBox.Show("connected");
  19. TaskNettyClient.isConnected = true;
  20. this.context = context;
  21. }
  22. public override void ChannelRead(IChannelHandlerContext context, object message)
  23. {
  24. if (message is Message msg)
  25. {
  26. toString(msg);
  27. messageQueue.Enqueue(msg);
  28. }
  29. }
  30. public override void ChannelReadComplete(IChannelHandlerContext context)
  31. {
  32. context.Flush();
  33. }
  34. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  35. {
  36. Console.WriteLine("Exception: " + exception);
  37. context.CloseAsync();
  38. }
  39. public override void ChannelInactive(IChannelHandlerContext context)
  40. {
  41. base.ChannelInactive(context);
  42. Console.WriteLine("1");
  43. TaskNettyClient.isConnected = false;
  44. }
  45. public override void ChannelUnregistered(IChannelHandlerContext context)
  46. {
  47. base.ChannelUnregistered(context);
  48. Console.WriteLine("2");
  49. }
  50. public override void HandlerRemoved(IChannelHandlerContext context)
  51. {
  52. base.HandlerRemoved(context);
  53. }
  54. public void toString(Message msg)
  55. {
  56. Console.WriteLine("Received from server: cmd : " + msg.Cmd + ", taskId : " + msg.TaskId + ", content : " + msg.Content);
  57. }
  58. public bool WriteMessage(Message message)
  59. {
  60. if (context == null || !context.Channel.Active)
  61. {
  62. return false;
  63. }
  64. try
  65. {
  66. context.WriteAndFlushAsync(message);
  67. }
  68. catch
  69. {
  70. return false;
  71. }
  72. return true;
  73. }
  74. }
  75. }