package com.eactive.httpmockserver.socket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; 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; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import javax.persistence.NoResultException; @Component public class EchoSocketServer { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private BytesMessageSpec spec; EventLoopGroup bossGroup; EventLoopGroup workerGroup; ChannelFuture channelFuture; public EchoSocketServer() { } public EchoSocketServer(BytesMessageSpec spec) { this.spec = spec; } public void start() throws Exception { if (spec == null) { throw new NoResultException(); } int port = (spec.getPort() == null ? 38181 : spec.getPort().intValue()); bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try { ServerBootstrap server = new ServerBootstrap(); // @formatter:off server.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LengthHeaderFrameDecoder(spec)); pipeline.addLast(new EchoSocketServerHandler(spec)); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, false); // @formatter:on channelFuture = server.bind(port).sync(); channelFuture.channel().closeFuture().sync().channel(); logger.info(port + " port bounded"); } catch (Exception e) { logger.error(e.getMessage()); throw e; } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } @PreDestroy public void stop() { try { bossGroup.shutdownGracefully().sync(); workerGroup.shutdownGracefully().sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.error(e.getMessage()); } } }