**
需求:监听指定多个端口,接收硬件消息,并向硬件发送问询帧。
**
问题记录:
1、netty使用自动注对象为空
解决办法:
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Autowired
private RedisUtil redisUtil;
@PostConstruct
public void init() {
nettyServerHandler = this;
}
/**
* 调用方式:nettyServerHandler.redisUtil
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean b = nettyServerHandler.redisUtil.hasKey("@emp");
}
2、监听多个端口
解决办法:
public void run() throws Exception {
EventLoopGroup leader = new NioEventLoopGroup();
EventLoopGroup coder = new NioEventLoopGroup();
try {
// 服务端启动引导器
ServerBootstrap server = new ServerBootstrap();
server
//把事件处理线程池添加进启动引导器
.group(leader, coder)
//设置通道的建立方式
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
//构造一个通道管道流水线
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 此处添加服务端的通道处理器,不同的端口用不同的类处理
int localPort = socketChannel.localAddress().getPort();
if (localPort == 7760) {
socketChannel.pipeline().addLast(new NettyServerHandler());
} else if (localPort == 7761) {
socketChannel.pipeline().addLast(new NettyServerHandler2());
}
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 服务端绑定端口并且开始接收进来的连接请求
ChannelFuture channelFuture = server.bind(port).sync();
ChannelFuture channelFuture2 = server.bind(port2).sync();
//通过回调只关闭自己监听的channel
channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
future.channel().close();
}
});
channelFuture2.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
future.channel().close();
}
});
// 查看一下操作是不是成功结束了
if (channelFuture.isSuccess()) {
//如果没有成功结束就处理一些事情,结束了就执行关闭服务端等操作
System.out.println("服务端启动成功,监听端口是:" + port);
}
if (channelFuture2.isSuccess()) {
//如果没有成功结束就处理一些事情,结束了就执行关闭服务端等操作
System.out.println("服务端启动成功,监听端口是:" + port2);
}
} finally {
// 关闭事件处理组
// leader.shutdownGracefully();
// coder.shutdownGracefully();
// System.out.println("服务端已关闭!");
}
}
3、远程主机强迫关闭了一个现有的连接。
这个问题没解决,搜索看大家说是因为在读写操作的时候断开连接了,因为我使用redis,这个问题影响不大。
欢迎讨论。