public RemoteServerListener(String password, boolean useNio) { this.interServerPassword = password; ChannelFactory chFactory; if (useNio) { chFactory = new NioServerSocketChannelFactory( Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool() ); } else { chFactory = new OioServerSocketChannelFactory( Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool() ); } this.bootstrap = new ServerBootstrap(chFactory); this.bootstrap.setPipelineFactory(() -> { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new InterServerPacketDecoder()); pipeline.addLast("encoder", new InterServerPacketEncoder()); pipeline.addLast("handler", new CenterServerHandler()); return pipeline; }); bootstrap.setOption("child.bufferFactory", new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN)); }
public boolean bind(int port) { try { bootstrap.bind(new InetSocketAddress(port)); LOG.log(Level.INFO, "Listening on port {0}", port); return true; } catch (ChannelException ex) { LOG.log(Level.SEVERE, "Could not bind on port " + port, ex); return false; } } public void init() {
listener = new RemoteServerListener(authKey, useNio); if (listener.bind(port)) LOG.log(Level.INFO, "Center Server is online.");
} public static final ChannelLocal<CenterRemoteSession> sessions = new ChannelLocal<CenterRemoteSession>();
private class CenterServerHandler extends SimpleChannelUpstreamHandler {
@Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.log(Level.FINEST, "Trying to accept remote server from {0}", e.getChannel().getRemoteAddress()); }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.log(Level.FINE, "Remote server connected from {0}", e.getChannel().getRemoteAddress()); sessions.set(e.getChannel(), new CenterRemoteSession(e.getChannel(), interServerPassword)); }
@Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.log(Level.FINE, "Remote server from {0} disconnected", e.getChannel().getRemoteAddress()); sessions.get(e.getChannel()).disconnected(); }
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.log(Level.FINEST, "Removing remote server from {0}", e.getChannel().getRemoteAddress()); sessions.remove(e.getChannel()); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { sessions.get(e.getChannel()).process((byte[]) e.getMessage()); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { LOG.log(Level.FINE, "Exception raised in internal network facing code (remote server " + e.getChannel().getRemoteAddress() + ")", e.getCause()); } } private class GameServerHandler extends IdleStateAwareChannelUpstreamHandler {
}