com.github.raduciumag.shapeshift.server.impl.echo.EchoServer Maven / Gradle / Ivy
package com.github.raduciumag.shapeshift.server.impl.echo;
import com.github.raduciumag.shapeshift.server.RootServerConfig;
import com.github.raduciumag.shapeshift.server.Server;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @since February 2016
*/
@Singleton
public class EchoServer extends Server {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
private final EchoServerConfig echoServerConfig;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
@Inject
public EchoServer(final RootServerConfig config) {
super(config);
this.echoServerConfig = config.getServer().getEchoServer();
}
@Override
protected void startInternal() throws Exception {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
try {
final ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(final SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
final ChannelFuture channelFuture = bootstrap.bind(echoServerConfig.getPort()).sync();
LOG.info("ECHO server available @ 127.0.0.1:{}", echoServerConfig.getPort());
waitChannelClosing(channelFuture);
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
@Override
protected void stopInternal() throws Exception {
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
}
}