1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.socksproxy;
17
18 import io.netty.buffer.Unpooled;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelInboundHandlerAdapter;
22 import io.netty.util.ReferenceCountUtil;
23
24 public final class RelayHandler extends ChannelInboundHandlerAdapter {
25
26 private final Channel relayChannel;
27
28 public RelayHandler(Channel relayChannel) {
29 this.relayChannel = relayChannel;
30 }
31
32 @Override
33 public void channelActive(ChannelHandlerContext ctx) {
34 ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
35 }
36
37 @Override
38 public void channelRead(ChannelHandlerContext ctx, Object msg) {
39 if (relayChannel.isActive()) {
40 relayChannel.writeAndFlush(msg);
41 } else {
42 ReferenceCountUtil.release(msg);
43 }
44 }
45
46 @Override
47 public void channelInactive(ChannelHandlerContext ctx) {
48 if (relayChannel.isActive()) {
49 SocksServerUtils.closeOnFlush(relayChannel);
50 }
51 }
52
53 @Override
54 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
55 cause.printStackTrace();
56 ctx.close();
57 }
58 }