123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using System;
- using System.Text;
- using System.Threading.Channels;
- using System.Threading.Tasks;
- using DotNetty.Buffers;
- using DotNetty.Transport.Bootstrapping;
- using DotNetty.Transport.Channels;
- using DotNetty.Transport.Channels.Sockets;
- public class TcpClientHandler : ChannelHandlerAdapter
- {
- public override void ChannelActive(IChannelHandlerContext context)
- {
- // 发送初始消息
- string message = "{\r\n \"station\":\"Bengbu_South_Station\",\r\n \"device\":\"KX211\",\r\n\"timestamp\":\"2024-10-09 12:12:12\",\r\n\"reason\":1,\r\n\"param\":{\r\n \"type\":\"Version_Information\",\r\n\"paras\":\r\n {\r\n \"program_version\":\"V6.0.0931\",\r\n \"program_verification_code\":\"7D4B\",\r\n \"equipment_type\":\"KF6520V6\",\r\n\"database_version\":\"20B60001\",\r\n\"logic_version\":\"000135BC1670(V7.0)\",\r\n\"hardware_version\":\"KF6500V6-CPU-P10-V1.1-V1.3\",\r\n\"boot_version\":\"1.03\",\r\n\"IEC61850_version\":\"V1.8.1\",\r\n\"FPGA_version\":\"NULL\",\r\n\"cid_file_CRC\":\"0xeeaa33cc\",\r\n\"ccd_file_CRC\":0xCEE5D436\r\n}\r\n}\r\n}\r\n";
- byte[] messageBytes = Encoding.UTF8.GetBytes(message);
- IByteBuffer buffer = Unpooled.WrappedBuffer(messageBytes);
- context.WriteAndFlushAsync(buffer);
- Console.WriteLine("Sent: " + message);
- }
- public override void ChannelRead(IChannelHandlerContext context, object message)
- {
- // 读取从服务器接收到的消息
- var byteBuffer = message as IByteBuffer;
- string response = byteBuffer.ToString(Encoding.UTF8);
- Console.WriteLine("Received: " + response);
- }
- public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
- {
- Console.WriteLine($"Exception: {exception}");
- context.CloseAsync();
- }
- }
- public class TcpClient
- {
- private TcpClientHandler _handler = new TcpClientHandler();
- public async Task RunClientAsync(string host, int port)
- {
- var group = new MultithreadEventLoopGroup();
- try
- {
- var bootstrap = new Bootstrap();
- bootstrap
- .Group(group)
- .Channel<TcpSocketChannel>()
- .Option(ChannelOption.TcpNodelay, true)
- .Handler(new ActionChannelInitializer<IChannel>(channel =>
- {
- IChannelPipeline pipeline = channel.Pipeline;
- pipeline.AddLast(_handler);
- pipeline.AddLast(new TcpClientHandler());
- }));
- IChannel clientChannel = await bootstrap.ConnectAsync(host, port);
- Console.WriteLine($"Connected to {host}:{port}");
- // 等待关闭
- await clientChannel.CloseAsync();
- }
- finally
- {
- await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
- }
- }
- public static async Task Main(string[] args)
- {
- var client = new TcpClient();
- string host = "127.0.0.1";
- int port = 7110;
- await client.RunClientAsync(host, port);
- }
- }
|