package com.inspect.tcpserver.tcp; import com.inspect.tcpserver.util.Color; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NettyServerHandler extends ChannelInboundHandlerAdapter { public Logger logger = LoggerFactory.getLogger(NettyServerHandler.class); private NettyServer nettyServer; public NettyServerHandler(NettyServer nettyServer) { this.nettyServer = nettyServer; } public void sendMsg(String uuid, String clientKey, ByteBuf byteBuf, String xml) { ChannelHandlerContext ctx = ChannelCache.getInstance().get(clientKey); if(ctx != null) { ctx.writeAndFlush(Unpooled.wrappedBuffer(byteBuf)).addListener( (ChannelFuture future) -> { if (future.isSuccess()) { logger.info(Color.CYAN + "###### 活动连接:{},向客户端[{}]下发消息成功:{}######" + Color.END, ChannelCache.getInstance().getClients(), clientKey, xml); } else { logger.error(Color.RED + "###### 活动连接:{},向客户端[{}]下发消息失败:{}######" + Color.END, ChannelCache.getInstance().getClients(), clientKey, xml); } }); } else { logger.error(Color.RED + "###### 活动连接:{},无法向客户端[{}]下发消息,ctx==null######" + Color.END, ChannelCache.getInstance().getClients(), clientKey); } } /** * 客户端连接会触发 */ @Override public void channelActive(ChannelHandlerContext ctx) { String id = ctx.channel().id().asShortText(); ChannelCache.getInstance().addIfAbsent(id, ctx); logger.info("###### 设备上线:{} ######", id); } /** * 客户端断开会触发 */ @Override public void channelInactive(ChannelHandlerContext ctx) { String id = ctx.channel().id().asShortText(); logger.info("###### 设备断开:{} ######", id); ChannelCache.getInstance().remove(ctx); } /** * 客户端发消息会触发 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { String id = ctx.channel().id().asShortText(); BinaryModel binaryModel = (BinaryModel) msg; binaryModel.id = id; nettyServer.receiveMsg((BinaryModel) msg, ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { super.channelReadComplete(ctx); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error( "channel ctx: " + ctx.channel() + " exception", cause); } }