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