package com.ld.io.netty; import com.ld.io.api.InvokeResult; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NettyChannel { private final Logger logger = LoggerFactory.getLogger(getClass()); private ChannelHandlerContext ctx; NettyChannel(ChannelHandlerContext ctx) { this.ctx = ctx; } public ChannelHandlerContext getCtx() { return ctx; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NettyChannel that = (NettyChannel) o; return ctx.equals(that.ctx); } @Override public int hashCode() { return ctx.hashCode(); } InvokeResult invoke(byte[] bytes) { if (ctx == null) { return InvokeResult.SOCKET_NOT_CREATE; } if (!ctx.channel().isActive()) { ctx.close(); return InvokeResult.CHANNEL_CLOSED; } ByteBuf buf = Unpooled.copiedBuffer(bytes); try { ctx.writeAndFlush(buf).sync(); } catch (Exception e) { logger.error("Invoke happened error", e); return InvokeResult.SOCKET_STATE_ERROR; } return InvokeResult.SUCCESS; } public void destroy() { try { ctx.close(); } catch (Exception e) { e.printStackTrace(); } } }