From 858cc2965f97e50c4cc9661a540ed4f1e1d8d475 Mon Sep 17 00:00:00 2001 From: DmitriyMX Date: Tue, 10 Apr 2018 02:49:22 +0300 Subject: [PATCH] Simple server --- .../mc/core/netty/proto_125/NettyServer.java | 57 +++++++++++++++++++ src/main/resources/spring.xml | 2 +- 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/main/java/mc/core/netty/proto_125/NettyServer.java diff --git a/src/main/java/mc/core/netty/proto_125/NettyServer.java b/src/main/java/mc/core/netty/proto_125/NettyServer.java new file mode 100644 index 0000000..c397f6b --- /dev/null +++ b/src/main/java/mc/core/netty/proto_125/NettyServer.java @@ -0,0 +1,57 @@ +/* + * DmitriyMX + * 2018-04-10 + */ +package mc.core.netty.proto_125; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelInitializer; +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 io.netty.handler.logging.LoggingHandler; +import lombok.extern.slf4j.Slf4j; +import mc.core.Server; +import mc.core.StartServerException; + +@Slf4j +public class NettyServer implements Server { + private EventLoopGroup bossGroup, workerGroup; + + private ChannelInitializer buildChannelInitializer() { + return new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) { + socketChannel.pipeline().addLast( + new LoggingHandler() + ); + } + }; + } + + private ServerBootstrap buildServerBootstrap() { + ServerBootstrap bootstrap = new ServerBootstrap(); + + bootstrap.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .childHandler(buildChannelInitializer()); + + return bootstrap; + } + + @Override + public void start(String host, int port) throws StartServerException { + log.info("Use protocol 1.2.5"); + bossGroup = new NioEventLoopGroup(1); + workerGroup = new NioEventLoopGroup(); + + ServerBootstrap serverBootstrap = buildServerBootstrap(); + + try { + serverBootstrap.bind(host, port).sync().channel().closeFuture().sync(); + } catch (InterruptedException e) { + throw new StartServerException(e); + } + } +} diff --git a/src/main/resources/spring.xml b/src/main/resources/spring.xml index bbe0796..38241de 100644 --- a/src/main/resources/spring.xml +++ b/src/main/resources/spring.xml @@ -10,5 +10,5 @@ - + \ No newline at end of file