您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

78 行
3.1 KiB

  1. using DotNetty.Buffers;
  2. using DotNetty.Codecs;
  3. using DotNetty.Transport.Bootstrapping;
  4. using DotNetty.Transport.Channels;
  5. using DotNetty.Transport.Channels.Sockets;
  6. using DotNetty.Transport.Libuv;
  7. using JT808.DotNetty.Codecs;
  8. using JT808.DotNetty.Configurations;
  9. using JT808.DotNetty.Handlers;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Net;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace JT808.DotNetty
  16. {
  17. public class JT808SimpleTcpClient
  18. {
  19. private Bootstrap cb;
  20. private MultithreadEventLoopGroup clientGroup;
  21. private IChannel clientChannel;
  22. private IByteBufferAllocator clientBufferAllocator;
  23. public JT808SimpleTcpClient(EndPoint remoteAddress)
  24. {
  25. clientBufferAllocator = new PooledByteBufferAllocator();
  26. clientGroup = new MultithreadEventLoopGroup(1);
  27. cb = new Bootstrap()
  28. .Group(clientGroup)
  29. .Channel<TcpSocketChannel>()
  30. .Option(ChannelOption.TcpNodelay, true)
  31. .Option(ChannelOption.Allocator, clientBufferAllocator)
  32. .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
  33. {
  34. channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
  35. Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
  36. Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
  37. channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
  38. }));
  39. clientChannel = cb.ConnectAsync(remoteAddress).Result;
  40. }
  41. public JT808SimpleTcpClient(EndPoint remoteAddress, EndPoint localAddress)
  42. {
  43. clientBufferAllocator = new PooledByteBufferAllocator();
  44. clientGroup = new MultithreadEventLoopGroup(1);
  45. cb = new Bootstrap()
  46. .Group(clientGroup)
  47. .Channel<TcpSocketChannel>()
  48. .Option(ChannelOption.TcpNodelay, true)
  49. .Option(ChannelOption.Allocator, clientBufferAllocator)
  50. .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
  51. {
  52. channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
  53. Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
  54. Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
  55. channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
  56. }));
  57. clientChannel = cb.ConnectAsync(remoteAddress, localAddress).Result;
  58. }
  59. public void WriteAsync(byte[] data)
  60. {
  61. clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(data));
  62. }
  63. public void Down()
  64. {
  65. this.clientChannel?.CloseAsync().Wait();
  66. Task.WaitAll(this.clientGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
  67. }
  68. }
  69. }