Java Netty Demo

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.*;

import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;


import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;

public class NettyTest {
    public static void main(String[] args) throws InterruptedException {
        int port = 80;
        ServerBootstrap http = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(2);

        http.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpRequestDecoder());//请求解码器
                        pipeline.addLast(new HttpResponseEncoder());//响应编码器
                        pipeline.addLast(new HttpObjectAggregator(65535));
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new FormatRequestParamHandler());//入口逻辑处理
                        pipeline.addLast(new BusinessHandler());//下一个入口逻辑处理
                    }
                });
        Channel ch = http.bind(port).sync().channel();
        ch.closeFuture().sync(); // 等待服务端监听到端口关闭
        workGroup.shutdownGracefully();//回收资源
        bossGroup.shutdownGracefully();
    }

    static class FormatRequestParamHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
            boolean keepAlive = HttpUtil.isKeepAlive(request);//连接类型
            if (!request.decoderResult().isSuccess()) return;//判断解码是否成功
            if (request.uri().equals("/favicon.ico")) {//过滤图标请求
                FullHttpResponse response = getResponse("图标");
                sendAndCleanupConnection(ctx, response, keepAlive);
                return;
            }
            ctx.fireChannelRead("将当前处理的参数放下发");//往下发
        }
    }

    static class BusinessHandler extends SimpleChannelInboundHandler<String> {
        /**
         * 逻辑处理
         *
         * @param ctx
         * @param msg 上一个串口传入的参数
         * @throws Exception
         */
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            FullHttpResponse response = getResponse(msg);
            sendAndCleanupConnection(ctx, response, true);//在上一个串口需要把链接类型带过来  这里用
        }
    }

    private static FullHttpResponse getResponse(String respMsg) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.copiedBuffer(respMsg, CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");//设置响应头
        return response;
    }

    /**
     * 发送响应
     */
    public static void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response, boolean keepAliveStatus) {
        Channel channel = ctx.channel();
        AsciiString keepAlive = keepAliveStatus ? KEEP_ALIVE : CLOSE;
        response.headers().set(CONNECTION, keepAlive);// 如果不是长连接,设置 connection:close 头部
        HttpUtil.setContentLength(response, response.content().readableBytes());
        ChannelFuture writePromise = channel.writeAndFlush(response);    //发送内容
        if (!HttpUtil.isKeepAlive(response))
            writePromise.addListener(ChannelFutureListener.CLOSE); // 如果不是长连接,发送完成之后,关闭连接
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小钻风巡山

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

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

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

打赏作者

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

抵扣说明:

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

余额充值