1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.objectecho;
17
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.concurrent.atomic.AtomicLong;
21 import java.util.logging.Level;
22 import java.util.logging.Logger;
23
24 import org.jboss.netty.channel.ChannelEvent;
25 import org.jboss.netty.channel.ChannelHandlerContext;
26 import org.jboss.netty.channel.ChannelState;
27 import org.jboss.netty.channel.ChannelStateEvent;
28 import org.jboss.netty.channel.ExceptionEvent;
29 import org.jboss.netty.channel.MessageEvent;
30 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
31
32
33
34
35
36
37 public class ObjectEchoClientHandler extends SimpleChannelUpstreamHandler {
38
39 private static final Logger logger = Logger.getLogger(
40 ObjectEchoClientHandler.class.getName());
41
42 private final List<Integer> firstMessage;
43 private final AtomicLong transferredMessages = new AtomicLong();
44
45
46
47
48 public ObjectEchoClientHandler(int firstMessageSize) {
49 if (firstMessageSize <= 0) {
50 throw new IllegalArgumentException(
51 "firstMessageSize: " + firstMessageSize);
52 }
53 firstMessage = new ArrayList<Integer>(firstMessageSize);
54 for (int i = 0; i < firstMessageSize; i ++) {
55 firstMessage.add(i);
56 }
57 }
58
59 public long getTransferredMessages() {
60 return transferredMessages.get();
61 }
62
63 @Override
64 public void handleUpstream(
65 ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
66 if (e instanceof ChannelStateEvent &&
67 ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) {
68 logger.info(e.toString());
69 }
70 super.handleUpstream(ctx, e);
71 }
72
73 @Override
74 public void channelConnected(
75 ChannelHandlerContext ctx, ChannelStateEvent e) {
76
77 e.getChannel().write(firstMessage);
78 }
79
80 @Override
81 public void messageReceived(
82 ChannelHandlerContext ctx, MessageEvent e) {
83
84 transferredMessages.incrementAndGet();
85 e.getChannel().write(e.getMessage());
86 }
87
88 @Override
89 public void exceptionCaught(
90 ChannelHandlerContext ctx, ExceptionEvent e) {
91 logger.log(
92 Level.WARNING,
93 "Unexpected exception from downstream.",
94 e.getCause());
95 e.getChannel().close();
96 }
97 }