package com.sv.netty; import com.sv.netty.config.HeartBeat; import com.sv.netty.config.VenueMessage; import com.sv.netty.utils.EncodeMsg; import com.sv.netty.utils.JsonUtils; import com.sv.service.MessageService; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.UnknownHostException; /** * 通讯服务器请求处理 * * @author peakren * @date 05/12/2017 10:27 PM */ @ChannelHandler.Sharable public class ClientHandler extends SimpleChannelInboundHandler { private final Logger logger = LoggerFactory.getLogger(ClientHandler.class); /** * 当通道就绪就会触发 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); } /** * 当通道失效就会触发 * @param ctx * @throws Exception */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); } /** * 当通道有读取事件时触发 * @param ctx * @param msg * @throws Exception */ @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { logger.info("接收服务器响应msg:[" + msg + "]"); VenueMessage message = JsonUtils.decode(msg, VenueMessage.class); MessageService.getInstance().execute(message); } /** * 心跳 * @param ctx * @param evt */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws UnknownHostException { if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.ALL_IDLE) { ctx.write(EncodeMsg.INSTANCE.encode(getHbMessage())); ctx.flush(); } } } /** * 封装心跳请求包 * @throws Exception */ private HeartBeat getHbMessage() { HeartBeat hb = new HeartBeat(); hb.setDeviceName("dsadasdasd"); hb.setVenueId(123); return hb; } /** * 处理异常 * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.info("ClientHandler exceptionCaught"); cause.printStackTrace(); Channel channel = ctx.channel(); if(channel.isActive()) { ctx.close(); } } }