package com.ruoyi.dataInterchange.netty.client;
|
|
import com.ruoyi.dataInterchange.netty.server.NettyHandle;
|
import com.ruoyi.dataInterchange.util.jtt809.decoder.Jtt809Decoder;
|
import com.ruoyi.dataInterchange.util.jtt809.encoder.Jtt809Encoder;
|
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.timeout.IdleStateHandler;
|
|
import java.net.InetSocketAddress;
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* @author zhibing.pu
|
* @Date 2025/3/3 20:11
|
*/
|
public class NettyClient {
|
/**
|
* 连接IP
|
*/
|
private String host;
|
/**
|
* 连接端口号
|
*/
|
private int port;
|
|
|
|
|
public NettyClient(String host, int port) {
|
this.host = host;
|
this.port = port;
|
}
|
|
|
/**
|
* 执行启动连接
|
* @throws Exception
|
*/
|
public void start(int code) throws Exception {
|
EventLoopGroup nioEventLoopGroup = null;
|
try {
|
//创建Bootstrap对象用来引导启动客户端
|
Bootstrap bootstrap = new Bootstrap();
|
//创建EventLoopGroup对象并设置到Bootstrap中,EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据
|
nioEventLoopGroup = new NioEventLoopGroup();
|
//创建InetSocketAddress并设置到Bootstrap中,InetSocketAddress是指定连接的服务器地址
|
bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port))
|
.handler(new ChannelInitializer<SocketChannel>() {
|
//添加一个ChannelHandler,客户端成功连接服务器后就会被执行
|
@Override
|
protected void initChannel(SocketChannel socketChannel)
|
throws Exception {
|
ChannelPipeline pipeline = socketChannel.pipeline();
|
// 解码器
|
pipeline.addLast("decoder", new Jtt809Decoder());
|
// 编码器
|
pipeline.addLast("encoder", new Jtt809Encoder());
|
// 空闲检测处理器 触发空闲状态事件 读空闲:5秒 写空闲:7秒 读写空闲:10秒
|
pipeline.addLast(new IdleStateHandler(5,7,3, TimeUnit.SECONDS));
|
// 处理器
|
pipeline.addLast("handler", new NettyHandle());
|
}
|
});
|
// • 调用Bootstrap.connect()来连接服务器
|
ChannelFuture f = bootstrap.connect().sync();
|
//将通道添加到缓存中,便于后期直接使用
|
Channel channel = f.channel();
|
ChannelMap.addClientChannel(code, channel.id());
|
// • 最后关闭EventLoopGroup来释放资源
|
f.channel().closeFuture().sync();
|
} finally {
|
nioEventLoopGroup.shutdownGracefully().sync();
|
}
|
}
|
|
public static void main(String[] args) {
|
try {
|
new NettyClient("221.182.45.100", 1000).start(1);
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
}
|
}
|