Netty 实现HTTP通信

Netty 实现HTTP通信

1. 服务端实现

public class MyHttpServer {
     

    private ServerBootstrap serverBootstrap;
    private Integer port;

    public MyHttpServer(Integer port)  {
     
        this.port = port;
        serverBootstrap = new ServerBootstrap();
    }

    public MyHttpServer() {
     
        this(8888);
    }

    /**
     * 启动服务监听
     */
    public void start() {
     
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup();

        try {
     
            // http网络通信的通道类型依然是NioServerSocketChannel
            serverBootstrap.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new MyHttpInitializer());

            ChannelFuture bindFuture = serverBootstrap.bind().sync();
            ChannelFuture sync = bindFuture.channel().closeFuture().sync();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }
}

2. Handler实现

  • 此处使用了SimpleChannelInboundHandler, 这里的HttpObject实际上代表着浏览器的请求
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
     
    protected void channelRead0(
            ChannelHandlerContext ctx,
            HttpObject httpObject) throws Exception {
     
        //此处HttpObject默认是HttpRequest
        if (httpObject instanceof HttpRequest) {
     
            //解析请求
            DefaultHttpRequest request = (DefaultHttpRequest) httpObject;
            System.out.println(request.uri());
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello world netty http", CharsetUtil.UTF_8);

            //封装响应数据
            HttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    byteBuf);

            response.headers()
                    .set(HttpHeaderNames.CONTENT_TYPE, "text/plain")
                    .set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            //响应数据
            ctx.writeAndFlush(response);
        }
    }
}

3. 添加通道处理器

  • HttpServerCodec是Netty默认提供的解析HTTP请求的编解码器
public class MyHttpInitializer extends ChannelInitializer {
     
    protected void initChannel(Channel channel) throws Exception {
     
        // 添加HTTP协议的编解码处理器
        channel.pipeline().addLast(new HttpServerCodec());
        // 加入自己的处理器
        channel.pipeline().addLast(new MyHttpServerHandler());
    }
}

4. 客户端

public class Entry {
     
    public static void main(String[] args) {
     
        MyHttpServer myHttpServer = new MyHttpServer();
        myHttpServer.start();
    }
}

你可能感兴趣的:(Netty,Netty实现HTTP通信,Netty实现HTTP服务器)