Netty之实现简单的httpserver

这是一个关于如何使用Netty框架创建一个简单的HTTP服务器的示例。代码中定义了一个`SimpleHttpServerHandler`,处理GET和POST请求,并返回响应。服务器启动方法`NettyHttpServer.start()`绑定了指定的IP地址和端口,监听HTTP请求。
摘要由CSDN通过智能技术生成

1、pom

   <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.75.Final</version>
   </dependency>

2、SimpleHttpServerHandler

package com.example.demo.http;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;


@Slf4j
public class SimpleHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
        try {
            log.info("SimpleHttpServerHandler receive fullHttpRequest=" + fullHttpRequest);

            String result = doHandle(fullHttpRequest);
            log.info("SimpleHttpServerHandler,result=" + result);
            byte[] responseBytes = result.getBytes(StandardCharsets.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(responseBytes));
            response.headers().set("Content-Type", "text/html; charset=utf-8");
            response.headers().setInt("Content-Length", response.content().readableBytes());

            boolean isKeepAlive = HttpUtil.isKeepAlive(response);
            if (!isKeepAlive) {
                ctx.write(response).addListener(ChannelFutureListener.CLOSE);
            } else {
                response.headers().set("Connection", "keep-alive");
                ctx.write(response);
            }
        } catch (Exception e) {
            log.error("channelRead0 exception,", e);
        }
    }

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

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

    /**
     * 实际处理
     *
     * @param fullHttpRequest HTTP请求参数
     * @return
     */
    private String doHandle(FullHttpRequest fullHttpRequest) {
        if (HttpMethod.GET == fullHttpRequest.method()) {
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(fullHttpRequest.uri());
            Map<String, List<String>> params = queryStringDecoder.parameters();
            return JSON.toJSONString(params);
        } else if (HttpMethod.POST == fullHttpRequest.method()) {
            byte[] bytes = new byte[fullHttpRequest.content().readableBytes()];
            fullHttpRequest.content().readBytes(bytes);
            return new String(bytes, CharsetUtil.UTF_8);
        }

        return fullHttpRequest.method().name();
    }
}

3、httpserver

package com.example.demo.http;

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.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyHttpServer {

    /**
     * host
     */
    private final static String host = "127.0.0.1";

    /**
     * 端口号
     */
    private final static Integer port = 8085;
    public static void main(String[] args) {
        start();
    }

    /**
     * netty服务端启动方法
     */
    public static void start() {
        log.info("SimpleHttpServer start begin ");
        EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossEventLoopGroup, workerEventLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    //开启tcp nagle算法
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //开启长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel c) {
                            c.pipeline().addLast(new HttpServerCodec())
                                    .addLast(new HttpObjectAggregator(512 * 1024))
                                    .addLast(new SimpleHttpServerHandler());

                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();

            log.info("SimpleHttpServer start at port " + port);

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("SimpleHttpServer start exception,", e);
        } finally {
            log.info("SimpleHttpServer shutdown bossEventLoopGroup&workerEventLoopGroup gracefully");
            bossEventLoopGroup.shutdownGracefully();
            workerEventLoopGroup.shutdownGracefully();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值