HelloWebServer.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package hello;
  2. import java.net.InetSocketAddress;
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.buffer.PooledByteBufAllocator;
  5. import io.netty.channel.Channel;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.ServerChannel;
  9. import io.netty.channel.epoll.Epoll;
  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);
  28. } else {
  29. doRun(new NioEventLoopGroup(), NioServerSocketChannel.class);
  30. }
  31. }
  32. private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException {
  33. try {
  34. InetSocketAddress inet = new InetSocketAddress(port);
  35. ServerBootstrap b = new ServerBootstrap();
  36. b.option(ChannelOption.SO_BACKLOG, 1024);
  37. b.option(ChannelOption.SO_REUSEADDR, true);
  38. b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
  39. b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
  40. b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
  41. b.childOption(ChannelOption.SO_REUSEADDR, true);
  42. b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
  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. }