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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值