Communication.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using DotNetty.Transport.Bootstrapping;
  7. using DotNetty.Transport.Channels;
  8. using DotNetty.Buffers;
  9. namespace nettyCommunication
  10. {
  11. public class Communication:ICommunication
  12. {
  13. private IChannelHandlerContext ctx = null;
  14. public Communication(IChannelHandlerContext ctx)
  15. {
  16. this.ctx = ctx;
  17. }
  18. public void Connection()
  19. {
  20. //连接,并注册初始化。
  21. try
  22. {
  23. ClientDemo.RunClientAsync().Wait();
  24. }
  25. catch (Exception)
  26. {
  27. Console.WriteLine("服务没有开启,请检查服务器");
  28. }
  29. }
  30. public void SendMessage(object message)
  31. {
  32. var mess = message as MessageUTF8;
  33. IByteBuffer initialMessage = Unpooled.Buffer(ClientSettings.Size);
  34. byte[] byteMessage = JsonByByteToObjectTools.ObjToJsonByte(mess);
  35. initialMessage.WriteBytes(byteMessage);
  36. ctx.WriteAndFlushAsync(initialMessage);
  37. }
  38. public AbstractMessage ReceiveMessage(object message)
  39. {
  40. try
  41. {
  42. AbstractMessage msg = null;
  43. IByteBuffer byteBuffer = message as IByteBuffer;
  44. byteBuffer.AdjustCapacity(1024);
  45. byteBuffer.SetWriterIndex(256);
  46. byte[] bytes = new byte[256];
  47. byteBuffer.SetReaderIndex(0);
  48. byteBuffer.ReadBytes(bytes);
  49. byteBuffer.Clear();
  50. MessageUTF8 mess = (MessageUTF8)JsonByByteToObjectTools.JsonByteToObj<MessageUTF8>(bytes);
  51. if (mess != null)
  52. {
  53. msg = mess;
  54. }
  55. else
  56. {
  57. msg = null;
  58. }
  59. return msg;
  60. }
  61. catch(Exception)
  62. {
  63. Console.WriteLine("消息对象转换存在问题,可能是服务器没有发送消息对象!");
  64. return null;
  65. }
  66. }
  67. public void Close()
  68. {
  69. throw new NotImplementedException();
  70. }
  71. }
  72. }