HttpProxyClientHandler.java
2.0 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
package com.github.monkeywie.proxyee.handler;
import com.github.monkeywie.proxyee.exception.HttpProxyExceptionHandle;
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.ReferenceCountUtil;
public class HttpProxyClientHandler extends ChannelInboundHandlerAdapter {
private Channel clientChannel;
public HttpProxyClientHandler(Channel clientChannel) {
this.clientChannel = clientChannel;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//客户端channel已关闭则不转发了
if (!clientChannel.isOpen()) {
ReferenceCountUtil.release(msg);
return;
}
HttpProxyInterceptPipeline interceptPipeline = ((HttpProxyServerHandler) clientChannel.pipeline()
.get("serverHandle")).getInterceptPipeline();
if (msg instanceof HttpResponse) {
interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpResponse) msg);
} else if (msg instanceof HttpContent) {
interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpContent) msg);
} else {
clientChannel.writeAndFlush(msg);
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
ctx.channel().close();
clientChannel.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.channel().close();
clientChannel.close();
HttpProxyExceptionHandle exceptionHandle = ((HttpProxyServerHandler) clientChannel.pipeline()
.get("serverHandle")).getExceptionHandle();
exceptionHandle.afterCatch(clientChannel, ctx.channel(), cause);
}
}