SimpleMessageHandler.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Cn.Sagacloud.Proto;
  2. using DotNetty.Transport.Channels;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace NettyClient
  10. {
  11. public class SimpleMessageHandler : ChannelHandlerAdapter
  12. {
  13. public SimpleMessageHandler() {
  14. }
  15. public static ConcurrentQueue<Message> messageQueue = new ConcurrentQueue<Message>();
  16. public IChannelHandlerContext context;
  17. public override void ChannelActive(IChannelHandlerContext context)
  18. {
  19. Console.WriteLine("connected");
  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 bool WriteMessage(Message message) {
  31. if (context == null || !context.Channel.Active) {
  32. return false;
  33. }
  34. try
  35. {
  36. context.WriteAndFlushAsync(message);
  37. }
  38. catch {
  39. return false;
  40. }
  41. return true;
  42. }
  43. public override void ChannelReadComplete(IChannelHandlerContext context)
  44. {
  45. context.Flush();
  46. }
  47. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  48. {
  49. Console.WriteLine("Exception: " + exception);
  50. context.CloseAsync();
  51. }
  52. //public override void ChannelInactive(IChannelHandlerContext context)
  53. //{
  54. // base.ChannelInactive(context);
  55. // Console.WriteLine("1");
  56. //}
  57. //public override void ChannelUnregistered(IChannelHandlerContext context)
  58. //{
  59. // base.ChannelUnregistered(context);
  60. // Console.WriteLine("2");
  61. //}
  62. public override void HandlerRemoved(IChannelHandlerContext context)
  63. {
  64. base.HandlerRemoved(context);
  65. }
  66. public void toString(Message msg)
  67. {
  68. Console.WriteLine("Received from server: cmd : " + msg.Cmd + ", taskId : " + msg.TaskId + ", content : " + msg.Content);
  69. }
  70. }
  71. }