HelloWebServer.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package hello;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.buffer.PooledByteBufAllocator;
  4. import io.netty.channel.Channel;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.ServerChannel;
  8. import io.netty.channel.epoll.Epoll;
  9. import io.netty.channel.epoll.EpollEventLoopGroup;
  10. import io.netty.channel.epoll.EpollServerSocketChannel;
  11. import io.netty.channel.nio.NioEventLoopGroup;
  12. import io.netty.channel.socket.nio.NioServerSocketChannel;
  13. import io.netty.util.ResourceLeakDetector;
  14. import io.netty.util.ResourceLeakDetector.Level;
  15. public class HelloWebServer {
  16. static {
  17. ResourceLeakDetector.setLevel(Level.DISABLED);
  18. }
  19. private final int port;
  20. public HelloWebServer(int port) {
  21. this.port = port;
  22. }
  23. public void run() throws Exception {
  24. // Configure the server.
  25. if (Epoll.isAvailable()) {
  26. doRun(new EpollEventLoopGroup(), EpollServerSocketChannel.class);
  27. } else {
  28. doRun(new NioEventLoopGroup(), NioServerSocketChannel.class);
  29. }
  30. }
  31. private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException {
  32. try {
  33. ServerBootstrap b = new ServerBootstrap();
  34. b.option(ChannelOption.SO_BACKLOG, 1024);
  35. b.option(ChannelOption.SO_REUSEADDR, true);
  36. b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
  37. b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
  38. b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
  39. b.childOption(ChannelOption.SO_REUSEADDR, true);
  40. b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
  41. Channel ch = b.bind(port).sync().channel();
  42. ch.closeFuture().sync();
  43. } finally {
  44. loupGroup.shutdownGracefully().sync();
  45. }
  46. }
  47. public static void main(String[] args) throws Exception {
  48. int port;
  49. if (args.length > 0) {
  50. port = Integer.parseInt(args[0]);
  51. } else {
  52. port = 8080;
  53. }
  54. new HelloWebServer(port).run();
  55. }
  56. }