1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.ipfilter;
17
18 import java.net.InetAddress;
19 import java.net.InetSocketAddress;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22
23 import org.jboss.netty.channel.ChannelEvent;
24 import org.jboss.netty.channel.ChannelHandler.Sharable;
25 import org.jboss.netty.channel.ChannelHandlerContext;
26 import org.jboss.netty.channel.ChannelState;
27 import org.jboss.netty.channel.ChannelStateEvent;
28
29
30
31
32
33
34
35
36
37
38 @Sharable
39 public class OneIpFilterHandler extends IpFilteringHandlerImpl {
40
41 private final ConcurrentMap<InetAddress, Boolean> connectedSet = new ConcurrentHashMap<InetAddress, Boolean>();
42
43 @Override
44 protected boolean accept(ChannelHandlerContext ctx, ChannelEvent e, InetSocketAddress inetSocketAddress)
45 throws Exception {
46 InetAddress inetAddress = inetSocketAddress.getAddress();
47 if (connectedSet.containsKey(inetAddress)) {
48 return false;
49 }
50 connectedSet.put(inetAddress, Boolean.TRUE);
51 return true;
52 }
53
54 @Override
55 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
56 super.handleUpstream(ctx, e);
57
58 if (e instanceof ChannelStateEvent) {
59 ChannelStateEvent evt = (ChannelStateEvent) e;
60 if (evt.getState() == ChannelState.CONNECTED) {
61 if (evt.getValue() == null) {
62
63 if (isBlocked(ctx)) {
64
65 InetSocketAddress inetSocketAddress = (InetSocketAddress) e.getChannel().getRemoteAddress();
66 connectedSet.remove(inetSocketAddress.getAddress());
67 }
68 }
69 }
70 }
71 }
72
73 }