Skip to content

Instantly share code, notes, and snippets.

@maxymania
Last active November 27, 2019 13:04
Show Gist options
  • Save maxymania/aa01a39468551738dd3cf1f3e373ee91 to your computer and use it in GitHub Desktop.
Save maxymania/aa01a39468551738dd3cf1f3e373ee91 to your computer and use it in GitHub Desktop.
Netty Bootstrap/Server Bootstrap abstraction
// Public Domain!
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
*
* @author simon
*/
public class NioTransport extends Transport{
@Override
protected EventLoopGroup socketLoop(boolean serverSide) {
return new NioEventLoopGroup();
}
@Override
protected EventLoopGroup listenerLoop() {
return new NioEventLoopGroup(1);
}
@Override
protected Class<? extends Channel> clientSocketType() {
return NioSocketChannel.class;
}
@Override
protected Class<? extends ServerChannel> serverSocketType() {
return NioServerSocketChannel.class;
}
}
// Public Domain!
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
*
* @author simon
*/
public abstract class Transport {
protected abstract EventLoopGroup socketLoop(boolean serverSide);
protected abstract EventLoopGroup listenerLoop();
protected abstract Class<? extends Channel> clientSocketType();
protected abstract Class<? extends ServerChannel> serverSocketType();
protected void clientOptions(Bootstrap clientBoot){}
protected void serverOptions(ServerBootstrap srvBoot){}
public Bootstrap client(ChannelHandler ch){
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(socketLoop(false));
clientBootstrap.channel(clientSocketType());
clientOptions(clientBootstrap);
clientBootstrap.handler(ch);
return clientBootstrap;
}
public ServerBootstrap server(ChannelHandler ch){
ServerBootstrap srvBoot = new ServerBootstrap();
srvBoot.group(listenerLoop(), socketLoop(true));
srvBoot.channel(serverSocketType());
srvBoot.handler(new LoggingHandler(LogLevel.INFO));
serverOptions(srvBoot);
srvBoot.childHandler(ch);
return srvBoot;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment