|
| 1 | +package com.baeldung.netty; |
| 2 | + |
| 3 | +import io.netty.bootstrap.ServerBootstrap; |
| 4 | +import io.netty.channel.ChannelFuture; |
| 5 | +import io.netty.channel.ChannelInitializer; |
| 6 | +import io.netty.channel.ChannelOption; |
| 7 | +import io.netty.channel.EventLoopGroup; |
| 8 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 9 | +import io.netty.channel.socket.SocketChannel; |
| 10 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 11 | + |
| 12 | +public class NettyServer { |
| 13 | + |
| 14 | + private int port; |
| 15 | + |
| 16 | + public NettyServer(int port) { |
| 17 | + this.port = port; |
| 18 | + } |
| 19 | + |
| 20 | + public static void main(String[] args) throws Exception { |
| 21 | + int port; |
| 22 | + if (args.length > 0) { |
| 23 | + port = Integer.parseInt(args[0]); |
| 24 | + } else { |
| 25 | + port = 8080; |
| 26 | + } |
| 27 | + new NettyServer(port).run(); |
| 28 | + } |
| 29 | + |
| 30 | + public void run() throws Exception { |
| 31 | + EventLoopGroup bossGroup = new NioEventLoopGroup(); |
| 32 | + EventLoopGroup workerGroup = new NioEventLoopGroup(); |
| 33 | + try { |
| 34 | + ServerBootstrap b = new ServerBootstrap(); |
| 35 | + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { |
| 36 | + @Override |
| 37 | + public void initChannel(SocketChannel ch) throws Exception { |
| 38 | + ch.pipeline().addLast(new RequestDecoder(), new ResponseDataEncoder(), new ProcessingHandler()); |
| 39 | + } |
| 40 | + }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); |
| 41 | + |
| 42 | + ChannelFuture f = b.bind(port).sync(); |
| 43 | + f.channel().closeFuture().sync(); |
| 44 | + } finally { |
| 45 | + workerGroup.shutdownGracefully(); |
| 46 | + bossGroup.shutdownGracefully(); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments