All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.raduciumag.shapeshift.server.impl.echo.EchoServer Maven / Gradle / Ivy

There is a newer version: 0.5.0
Show newest version
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();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy