|
| 1 | +package com.ipman.netty.springboot.sample.http; |
| 2 | + |
| 3 | +import io.netty.bootstrap.ServerBootstrap; |
| 4 | +import io.netty.channel.*; |
| 5 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 6 | +import io.netty.channel.socket.SocketChannel; |
| 7 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 8 | +import io.netty.handler.codec.http.HttpServerCodec; |
| 9 | +import io.netty.handler.codec.http.HttpServerExpectContinueHandler; |
| 10 | +import io.netty.handler.logging.LogLevel; |
| 11 | +import io.netty.handler.logging.LoggingHandler; |
| 12 | + |
| 13 | +/** |
| 14 | + * Created by ipipman on 2022/1/19. |
| 15 | + * |
| 16 | + * @version V1.0 |
| 17 | + * @Package com.ipman.netty.springboot.sample.http |
| 18 | + * @Description: (用一句话描述该文件做什么) |
| 19 | + * @date 2022/1/19 10:00 下午 |
| 20 | + */ |
| 21 | +public class HttpServer { |
| 22 | + |
| 23 | + public static void main(String[] args) { |
| 24 | + // 主从模式 |
| 25 | + EventLoopGroup bossGroup = new NioEventLoopGroup(1); |
| 26 | + EventLoopGroup workerGroup = new NioEventLoopGroup(); |
| 27 | + |
| 28 | + try { |
| 29 | + ServerBootstrap b = new ServerBootstrap(); |
| 30 | + b.group(bossGroup, workerGroup) |
| 31 | + .channel(NioServerSocketChannel.class) |
| 32 | + .handler(new LoggingHandler(LogLevel.INFO)) |
| 33 | + .childHandler(new ChannelInitializer<SocketChannel>() { |
| 34 | + @Override |
| 35 | + protected void initChannel(SocketChannel ch) throws Exception { |
| 36 | + // HTTP 模式 |
| 37 | + ChannelPipeline p = ch.pipeline(); |
| 38 | + p.addLast(new HttpServerCodec()); |
| 39 | + p.addLast(new HttpServerExpectContinueHandler()); |
| 40 | + p.addLast(new HttpServerHandler()); |
| 41 | + } |
| 42 | + }); |
| 43 | + ChannelFuture ch = b.bind(8099).sync(); |
| 44 | + |
| 45 | + System.out.println("Open Http Server : http://127.0.0.1:8099"); |
| 46 | + ch.channel().closeFuture().sync(); |
| 47 | + |
| 48 | + } catch (Exception ex) { |
| 49 | + ex.printStackTrace(); |
| 50 | + } finally { |
| 51 | + workerGroup.shutdownGracefully(); |
| 52 | + bossGroup.shutdownGracefully(); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments