ClientDemoHandler.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using DotNetty.Buffers;
  7. using DotNetty.Transport.Channels;
  8. namespace nettyCommunication
  9. {
  10. public class ClientDemoHandler: ChannelHandlerAdapter
  11. {
  12. readonly IByteBuffer initialMessage;
  13. public static object Message { get; set; }
  14. public static IChannelHandlerContext CTX { get; set; }
  15. public ClientDemoHandler()
  16. {
  17. MessageUTF8 ms = new MessageUTF8();
  18. ms.cmd = "R";
  19. ms.garageID = ClientSettings.GarageID;
  20. ms.context = "hello wit";
  21. byte[] byteMessage = JsonByByteToObjectTools.ObjToJsonByte(ms);
  22. this.initialMessage = Unpooled.Buffer(ClientSettings.Size);
  23. this.initialMessage.WriteBytes(byteMessage);
  24. }
  25. public override void ChannelActive(IChannelHandlerContext context)
  26. {
  27. //base.ChannelActive(context);
  28. CTX = context;
  29. Console.WriteLine("ChannelActive");
  30. context.WriteAndFlushAsync(this.initialMessage);
  31. Console.WriteLine("连接建立,将初始化(注册信息发给服务器)");
  32. }
  33. public override void ChannelRead(IChannelHandlerContext context, object message)
  34. {
  35. Message = message;
  36. }
  37. public override void ChannelReadComplete(IChannelHandlerContext context)
  38. {
  39. context.Flush();
  40. }
  41. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  42. {
  43. Console.WriteLine("Exception:"+exception);
  44. context.CloseAsync();
  45. }
  46. }
  47. }