DiscardServer

 1 package io.netty.example.discard;
 2     
 3 import io.netty.bootstrap.ServerBootstrap;
 4 
 5 import io.netty.channel.ChannelFuture;
 6 import io.netty.channel.ChannelInitializer;
 7 import io.netty.channel.ChannelOption;
 8 import io.netty.channel.EventLoopGroup;
 9 import io.netty.channel.nio.NioEventLoopGroup;
10 import io.netty.channel.socket.SocketChannel;
11 import io.netty.channel.socket.nio.NioServerSocketChannel;
12     
13 /**
14  * Discards any incoming data.
15  */
16 public class DiscardServer {
17     
18     private int port;
19     
20     public DiscardServer(int port) {
21         this.port = port;
22     }
23     
24     public void run() throws Exception {
25         EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
26         EventLoopGroup workerGroup = new NioEventLoopGroup();
27         try {
28             ServerBootstrap b = new ServerBootstrap(); // (2)
29             b.group(bossGroup, workerGroup)
30              .channel(NioServerSocketChannel.class) // (3)
31              .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
32                  @Override
33                  public void initChannel(SocketChannel ch) throws Exception {
34                      ch.pipeline().addLast(new DiscardServerHandler());
35                  }
36              })
37              .option(ChannelOption.SO_BACKLOG, 128)          // (5)
38              .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
39     
40             // Bind and start to accept incoming connections.
41             ChannelFuture f = b.bind(port).sync(); // (7)
42     
43             // Wait until the server socket is closed.
44             // In this example, this does not happen, but you can do that to gracefully
45             // shut down your server.
46             f.channel().closeFuture().sync();
47         } finally {
48             workerGroup.shutdownGracefully();
49             bossGroup.shutdownGracefully();
50         }
51     }
52     
53     public static void main(String[] args) throws Exception {
54         int port;
55         if (args.length > 0) {
56             port = Integer.parseInt(args[0]);
57         } else {
58             port = 8080;
59         }
60         new DiscardServer(port).run();
61     }
62 }
View Code

相关文章:

  • 2021-06-24
  • 2021-10-31
  • 2022-01-30
  • 2021-12-09
  • 2021-07-29
  • 2021-08-21
猜你喜欢
  • 2021-09-09
  • 2021-11-27
  • 2021-08-10
  • 2021-06-04
  • 2021-07-09
  • 2021-08-30
  • 2021-10-21
相关资源
相似解决方案