Java tutorial
/* * Here comes the text of your license * Each line should be prefixed with * */ package com.witjit.game.server.communication.netty.handler; import com.witjit.game.server.communication.node.RemoteNodeManager; import com.witjit.game.server.communication.node.RemoteNode; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Administrator */ @Sharable public class NodeChannelInitializer<M> extends ChannelInboundHandlerAdapter { private final Logger log = LoggerFactory.getLogger(getClass()); private final short localNodeId; private RemoteNodeManager<M> remoteNodeManager; private NodeChannelBuilder channelBuilder; public NodeChannelInitializer(short localNodeId) { this.localNodeId = localNodeId; } public void initialize(RemoteNodeManager<M> remoteNodeManager, NodeChannelBuilder channelBuilder) { this.channelBuilder = channelBuilder; this.remoteNodeManager = remoteNodeManager; } protected boolean bindNode(short nodeId, ChannelAdapter<M> adapter) { RemoteNode node = this.remoteNodeManager.getNode(nodeId); node.bind(adapter); return true; } protected void initChannel(Channel ch) throws Exception { channelBuilder.initChannel(ch); } protected void sendNodeInformation(Channel ch) throws Exception { ByteBuf buffer = Unpooled.buffer(4); buffer.writeShort(localNodeId); ch.writeAndFlush(buffer); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { sendNodeInformation(ctx.channel()); ctx.fireChannelRegistered(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!bindNode(ctx.channel(), (ByteBuf) msg)) { return; } initChannel(ctx.channel()); ctx.pipeline().remove(this); ctx.fireChannelRead(msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.fireExceptionCaught(cause); } private boolean bindNode(Channel channel, ByteBuf byteBuf) { int bytesCount = byteBuf.readableBytes(); if (bytesCount < 2) { return false; } short nodeId = byteBuf.readShort(); ChannelAdapter<M> adapter = new ChannelAdapter<M>(channel); return bindNode(nodeId, adapter); } }