123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using DotNetty.Transport.Bootstrapping;
- using DotNetty.Transport.Channels;
- using DotNetty.Transport.Channels.Sockets;
- using System;
- using System.Net;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using DotNetty.Codecs.Protobuf;
- using Message = Cn.Sagacloud.Proto.Message;
- namespace NettyClient
- {
- public class TaskNettyClient
- {
- private string ip;
- private int port;
- IChannel clientChannel;
- MultithreadEventLoopGroup group;
- Bootstrap bootstrap;
- public static bool isConnected = true;
- public TaskNettyClient(string ip, int port)
- {
- this.ip = ip;
- this.port = port;
- }
- public async Task RunClientAsync(ChannelHandlerAdapter channelHandler)
- {
- group = new MultithreadEventLoopGroup();
- try
- {
- bootstrap = new Bootstrap();
- bootstrap
- .Group(group)
- .Channel<TcpSocketChannel>()
- .Option(ChannelOption.TcpNodelay, true)
- .Handler(
- new ActionChannelInitializer<ISocketChannel>(
- channel =>
- {
-
- IChannelPipeline pipeline = channel.Pipeline;
- pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender());
- pipeline.AddLast(new ProtobufVarint32FrameDecoder());
- pipeline.AddLast("encoder", new ProtobufEncoder());
- pipeline.AddLast("decoder", new ProtobufDecoder(Message.Parser));
- pipeline.AddLast("simple", channelHandler);
- }));
- clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
-
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + $"ip:{ip};port{port}");
- }
- finally
- {
-
- }
- }
- public async Task CloseAsync()
- {
- try
- {
- await clientChannel.CloseAsync();
- }
- catch { }
- finally
- {
- await Task.WhenAll(group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
- }
- }
- public static void Main(string[] args)
- {
- TaskNettyClient client = new TaskNettyClient("47.94.89.44", 6666);
- SimpleMessageHandler simpleHandler = new SimpleMessageHandler();
- client.RunClientAsync(simpleHandler).Wait();
- while (true)
- {
- Thread.Sleep(15000);
-
- client.CloseAsync().Wait();
-
-
- }
- }
- }
- public static class NettyHelper
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
|