public void Start() { try { string Command = "Hello"; if (string.IsNullOrEmpty(Command)) { return; } IPAddress ServerIP = IPAddress.Parse("127.0.0.1"); // 服务器地址 int ServerPort = 8007; // 服务器端口 int ConnectTimeout = 10000; // 连接等待时间 int ReplyTimeout = 10000; // 回复等待时间 var param = new ClientParams() { ServerIP = ServerIP, ServerPort = ServerPort, ConnectTimeout = ConnectTimeout, ReplyTimeout = ReplyTimeout, ReceiveCompletedEvent = new ManualResetEvent(false), Command = Command }; Task.Run(() => RunClientAsync(param)); } catch (Exception exception) { } }
public async Task RunClientAsync(ClientParams args) { var group = new MultithreadEventLoopGroup(); X509Certificate2 cert = null; string targetHost = null; try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) //.Option(ChannelOption.ConnectTimeout, new TimeSpan(0, 0, 0, 0, args.ConnectTimeout)) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //出栈消息,通过这个handler 在消息顶部加上消息的长度 pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); //入栈消息,通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); //心跳检测每10秒进行一次读检测,如果10秒内ChannelRead()方法未被调用则触发一次userEventTrigger()方法. pipeline.AddLast("idleStateHandle", new IdleStateHandler(10, 0, 0)); //定义Handler类及名称 pipeline.AddLast("NettyClient", new ClientHandler()); })); clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(args.ServerIP, args.ServerPort)); ClosingArrivedEvent.Reset(); ClosingArrivedEvent.WaitOne(); await clientChannel.CloseAsync(); } catch (Exception exp) { MainWindow.SetText("Client connection failed"); } finally { //await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); ReConnectServer(); } }