Netty(二) 實現簡單Http伺服器

Polit丶發表於2020-11-14

 --------使用Netty簡單的實現Http伺服器

Netty相關元件可以去看我的上一篇部落格   Netty(一) 裡面有介紹

服務端:

/**
 * @Author Joker
 * @Date 2020/11/13
 * @since 1.8
 */
public class HttpServerDemo {
    public static void main(String[] args) {
        // 建立主從
        EventLoopGroup masterEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup slaveEventLoopGroup = new NioEventLoopGroup();

        // 建立服務啟動類
        ServerBootstrap bootstrap = new ServerBootstrap();
        // 繫結主從模式
        bootstrap.group(masterEventLoopGroup, slaveEventLoopGroup);
        // 繫結通道
        bootstrap.channel(NioServerSocketChannel.class);

        bootstrap.childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                // 新增Http編碼器,該解碼器會將字串轉成HttpRequest
                pipeline.addLast(new HttpServerCodec());
                // 將編碼器HttpRequest轉成FullHttpRequest物件
                pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
                pipeline.addLast(new HttpChannelHandler());
            }
        });
        ChannelFuture bind = bootstrap.bind("127.0.0.1", 8888);
        try {
            bind.sync();
            System.out.println("服務啟動成功");
            bind.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            masterEventLoopGroup.shutdownGracefully();
            slaveEventLoopGroup.shutdownGracefully();
        }
    }
}

 Http訊息處理器

/**
 * @Author Joker
 * @Date 2020/11/14
 * @since 1.8
 */
public class HttpChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        String name = fullHttpRequest.method().name();
        System.out.println("請求方法: " + name);

        HttpHeaders headers = fullHttpRequest.headers();
        List<Map.Entry<String, String>> entries = headers.entries();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        String con = fullHttpRequest.content().toString(Charset.defaultCharset());
        System.out.println("內容: " + con);

        // 相應頁面,設定相應資訊
        String respMsg = "<html>Hello World</html>";
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().add("context-type", "text/html;charset=utf-8");
        response.content().writeBytes(respMsg.getBytes("UTF-8"));
        channelHandlerContext.writeAndFlush(response);
    }

執行服務端,可以通過網頁訪問地址

 我們的訊息處理器就會把我們請求的相關資訊列印出來...

好啦,這就是一個使用Netty簡單實現的Http伺服器

相關文章