HttpServerInboundHandler.java
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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);
}
}