SimpleMessageHandler.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using DotNetty.Transport.Channels;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Windows.Forms;
  5. using Message = NettyClient.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. this.context = context;
  20. }
  21. public override void ChannelRead(IChannelHandlerContext context, object message)
  22. {
  23. if (message is Message msg)
  24. {
  25. toString(msg);
  26. messageQueue.Enqueue(msg);
  27. }
  28. }
  29. public override void ChannelReadComplete(IChannelHandlerContext context)
  30. {
  31. context.Flush();
  32. }
  33. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  34. {
  35. Console.WriteLine("Exception: " + exception);
  36. context.CloseAsync();
  37. }
  38. public override void ChannelInactive(IChannelHandlerContext context)
  39. {
  40. base.ChannelInactive(context);
  41. Console.WriteLine("1");
  42. }
  43. public override void ChannelUnregistered(IChannelHandlerContext context)
  44. {
  45. base.ChannelUnregistered(context);
  46. Console.WriteLine("2");
  47. }
  48. public override void HandlerRemoved(IChannelHandlerContext context)
  49. {
  50. base.HandlerRemoved(context);
  51. }
  52. public void toString(Message msg)
  53. {
  54. Console.WriteLine("Received from server: cmd : " + msg.Cmd + ", taskId : " + msg.TaskId + ", content : " + msg.Content);
  55. }
  56. public bool WriteMessage(Message message)
  57. {
  58. if (context == null || !context.Channel.Active)
  59. {
  60. return false;
  61. }
  62. try
  63. {
  64. context.WriteAndFlushAsync(message);
  65. }
  66. catch
  67. {
  68. return false;
  69. }
  70. return true;
  71. }
  72. }
  73. }