|  | 
|  | 1 | +import io.netty.bootstrap.ServerBootstrap; | 
|  | 2 | +import io.netty.channel.ChannelFuture; | 
|  | 3 | +import io.netty.channel.ChannelInitializer; | 
|  | 4 | +import io.netty.channel.ChannelOption; | 
|  | 5 | +import io.netty.channel.nio.NioEventLoopGroup; | 
|  | 6 | +import io.netty.channel.socket.SocketChannel; | 
|  | 7 | +import io.netty.channel.socket.nio.NioServerSocketChannel; | 
|  | 8 | + | 
| 1 | 9 | /** | 
| 2 | 10 |  * author yg | 
| 3 | 11 |  * description | 
| 4 | 12 |  * date 2020/1/28 | 
| 5 | 13 |  */ | 
| 6 | 14 | public class TimeServer { | 
| 7 |  | -    public static void main(String[] args) { | 
|  | 15 | +    private void bind(int port) throws Exception{ | 
|  | 16 | +        NioEventLoopGroup boss = new NioEventLoopGroup(); | 
|  | 17 | +        NioEventLoopGroup worker = new NioEventLoopGroup(); | 
|  | 18 | +        try { | 
|  | 19 | +            ServerBootstrap b = new ServerBootstrap(); | 
|  | 20 | +            b.group(boss, worker) | 
|  | 21 | +                    .channel(NioServerSocketChannel.class) | 
|  | 22 | +                    .option(ChannelOption.SO_BACKLOG, 1024) | 
|  | 23 | +                    .childHandler(new ChildChannelHandler()); | 
|  | 24 | +            ChannelFuture sync = b.bind(port).sync(); | 
|  | 25 | +            sync.channel().closeFuture().sync(); | 
|  | 26 | +        } finally { | 
|  | 27 | +            boss.shutdownGracefully(); | 
|  | 28 | +            worker.shutdownGracefully(); | 
|  | 29 | +        } | 
|  | 30 | + | 
|  | 31 | +    } | 
|  | 32 | + | 
|  | 33 | +    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { | 
|  | 34 | + | 
|  | 35 | +        @Override | 
|  | 36 | +        protected void initChannel(SocketChannel ch) throws Exception { | 
|  | 37 | +            ch.pipeline().addLast(new TimeServerHandler()); | 
|  | 38 | +        } | 
|  | 39 | +    } | 
| 8 | 40 | 
 | 
|  | 41 | +    public static void main(String[] args) throws Exception { | 
|  | 42 | +        int port=8080; | 
|  | 43 | +        new TimeServer().bind(port); | 
| 9 | 44 |     } | 
| 10 | 45 | } | 
0 commit comments