HelloWebServer.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package hello;
  2. import java.net.InetSocketAddress;
  3. import io.netty.bootstrap.ServerBootstrap;
  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.EpollChannelOption;
  10. import io.netty.channel.epoll.EpollEventLoopGroup;
  11. import io.netty.channel.epoll.EpollServerSocketChannel;
  12. import io.netty.channel.nio.NioEventLoopGroup;
  13. import io.netty.channel.socket.nio.NioServerSocketChannel;
  14. import io.netty.util.ResourceLeakDetector;
  15. import io.netty.util.ResourceLeakDetector.Level;
  16. public class HelloWebServer {
  17. static {
  18. ResourceLeakDetector.setLevel(Level.DISABLED);
  19. }
  20. private final int port;
  21. public HelloWebServer(int port) {
  22. this.port = port;
  23. }
  24. public void run() throws Exception {
  25. // Configure the server.
  26. if (Epoll.isAvailable()) {
  27. doRun(new EpollEventLoopGroup(), EpollServerSocketChannel.class, true);
  28. } else {
  29. doRun(new NioEventLoopGroup(), NioServerSocketChannel.class, false);
  30. }
  31. }
  32. private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass, boolean isNative) throws InterruptedException {
  33. try {
  34. InetSocketAddress inet = new InetSocketAddress(port);
  35. ServerBootstrap b = new ServerBootstrap();
  36. if (isNative) {
  37. b.option(EpollChannelOption.SO_REUSEPORT, true);
  38. }
  39. b.option(ChannelOption.SO_BACKLOG, 8192);
  40. b.option(ChannelOption.SO_REUSEADDR, true);
  41. b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
  42. b.childOption(ChannelOption.SO_REUSEADDR, true);
  43. Channel ch = b.bind(inet).sync().channel();
  44. System.out.printf("Httpd started. Listening on: %s%n", inet.toString());
  45. ch.closeFuture().sync();
  46. } finally {
  47. loupGroup.shutdownGracefully().sync();
  48. }
  49. }
  50. public static void main(String[] args) throws Exception {
  51. int port;
  52. if (args.length > 0) {
  53. port = Integer.parseInt(args[0]);
  54. } else {
  55. port = 8080;
  56. }
  57. new HelloWebServer(port).run();
  58. }
  59. }