HttpServerInboundHandler.java 2.2 KB
package com.zhonglai.socket.html.http.handler;

import com.zhonglai.socket.html.http.service.AnalysisService;
import com.zhonglai.socket.html.http.service.impl.DefaultAnalysisServiceImpl;
import com.zhonglai.socket.html.http.util.HttpResponseUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;

@ChannelHandler.Sharable
public class HttpServerInboundHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    AnalysisService analysisService = new DefaultAnalysisServiceImpl();


    public HttpServerInboundHandler(AnalysisService analysisService)
    {
        this.analysisService = analysisService;
    }

    public HttpServerInboundHandler()
    {

    }


    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        if (!request.decoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST);
            return;
        }
        if (request.method() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }
        final String uri = request.uri();
        System.out.println("come here messageReceived uri="+uri);

        //这里可以根据具体的url来拆分,获取请求带过来的参数,实现自己具体的业务操作
        analysisService.analysis(ctx,request);

        //sendError(ctx, UNAUTHORIZED);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }

    private static void sendError(ChannelHandlerContext ctx,
                                  HttpResponseStatus status) {
        ctx.writeAndFlush(HttpResponseUtil.newERResponse(status)).addListener(ChannelFutureListener.CLOSE);
    }

}