Netty 搭建Http服务端

本文档展示了如何使用Netty构建一个简单的HTTP服务器,并处理浏览器请求。在示例中,服务器返回'NettyHttpServer',但浏览器显示中文乱码。服务端日志正常,已设置响应头为UTF-8编码,问题可能出在浏览器解码上。源代码包括了HttpServerHandler和HttpNIOServer两个关键类。
摘要由CSDN通过智能技术生成

1. 通过浏览器请求接口,http://localhost:8000/

Netty的Http服务器返回 Netty Http Server

浏览器中文乱码:

response.headers().set(CONTENT_TYPE, "text/plain; Charset=UTF-8");

2. 服务端打印的日志

Netty的Http服务器源码如下:

package server;


import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.CharsetUtil;

import java.net.URLEncoder;

import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpHeaders.Values.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @auther: TF12778
 * @date: 2021/4/13 16:24
 * @description: 通过浏览器请求下面的接口,返回 OK OK OK OK
 * http://localhost:8000/
 */
public class HttpServerHandler extends ChannelInboundHandlerAdapter {

    private final static String responseMsg = "Netty Http Server";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        if (msg instanceof HttpRequest) {
            if ("/favicon.ico".equals(((HttpRequest) msg).getUri())) {
                System.out.println("对于请求图标的请求不做处理,return");
                return;
            }

            byte[] bytes = responseMsg.getBytes(CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes));
            response.headers().set(CONTENT_TYPE, "text/plain; Charset=UTF-8");

            response.headers().set(CONTENT_LENGTH,
                    response.content().readableBytes());
            response.headers().set(CONNECTION, KEEP_ALIVE);
            response.headers().set(CONTENT_ENCODING, "UTF-8" );
            ctx.writeAndFlush(response);
//            System.out.println("发送成功的数据为:" + Unpooled.wrappedBuffer("OK OK OK OK"
//                    .getBytes()).toString(CharsetUtil.UTF_8));
            System.out.println("发送成功的数据为:" + responseMsg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
    }

}
package server;

import com.sun.net.httpserver.HttpServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * @auther: TF12778
 * @date: 2021/4/13 16:23
 * @description:
 */
public class HttpNIOServer {
    public void start(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
                            ch.pipeline().addLast(
                                    new HttpResponseEncoder());
                            // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
                            ch.pipeline().addLast(
                                    new HttpRequestDecoder());
                            ch.pipeline().addLast(
                                    new HttpServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync();
            System.out.println("Http Server has started...");

            f.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpNIOServer server = new HttpNIOServer();
        server.start(8000);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值