| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package com.mes.netty;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.*;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- import io.netty.handler.codec.string.StringEncoder;
- import java.util.concurrent.TimeUnit;
- import com.mes.ui.MesClient;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class NettyClient {
- public static final Logger log = LoggerFactory.getLogger(NettyClientHandler.class);
- public SocketChannel socketChannel;
- public static ChannelFuture future;
- public void run(Object msg){
- //配置线程组
- EventLoopGroup group = new NioEventLoopGroup();
- //创建服务启动器
- Bootstrap bootstrap = new Bootstrap();
- //配置参数
- bootstrap.group(group)
- .channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY,true)
- .handler(new ChannelInitializer<SocketChannel>() {
- protected void initChannel(SocketChannel socketChannel) throws Exception {
- socketChannel.pipeline()
- .addLast(new XDecoder())
- .addLast(new StringEncoder())
- // .addLast(new StringDecoder())
- .addLast(new NettyClientHandler());
- }
- })
- .remoteAddress(MesClient.mes_server_ip,MesClient.mes_tcp_port);
- //连接
- future = bootstrap.connect();
- log.info("客户端正在连接服务端...");
- //客户端断线重连逻辑
- future.addListener((ChannelFutureListener) future1 -> {
- if (future1.isSuccess()) {
- //tcp连接成功
- MesClient.tcp_connect_flag = true;
- //设置TCP请求状态
- MesClient.connect_request_flag = false;
- log.info("连接Netty服务端成功");
- future.channel().writeAndFlush(msg);
- } else {
- //tcp连接失败
- MesClient.tcp_connect_flag = false;
- MesClient.connect_request_flag = true;
- log.info("连接失败,进行断线重连");
- future1.channel().eventLoop().schedule(() -> run(msg), 10, TimeUnit.SECONDS);
- }
- //设置tcp连接状态
- MesClient.setTcpStatus();
- });
- socketChannel = (SocketChannel) future.channel();
- }
- }
|