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 public class EchoClientHandler extends SimpleChannelUpstreamHandler {
36
37 private static final Logger logger = Logger.getLogger(
38 EchoClientHandler.class.getName());
39
40 private final ChannelBuffer firstMessage;
41 private final AtomicLong transferredBytes = new AtomicLong();
42
43
44
45
46 public EchoClientHandler(int firstMessageSize) {
47 if (firstMessageSize <= 0) {
48 throw new IllegalArgumentException(
49 "firstMessageSize: " + firstMessageSize);
50 }
51 firstMessage = ChannelBuffers.buffer(firstMessageSize);
52 for (int i = 0; i < firstMessage.capacity(); i ++) {
53 firstMessage.writeByte((byte) i);
54 }
55 }
56
57 public long getTransferredBytes() {
58 return transferredBytes.get();
59 }
60
61 @Override
62 public void channelConnected(
63 ChannelHandlerContext ctx, ChannelStateEvent e) {
64
65
66 e.getChannel().write(firstMessage);
67 }
68
69 @Override
70 public void messageReceived(
71 ChannelHandlerContext ctx, MessageEvent e) {
72
73 transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
74 e.getChannel().write(e.getMessage());
75 }
76
77 @Override
78 public void exceptionCaught(
79 ChannelHandlerContext ctx, ExceptionEvent e) {
80
81 logger.log(
82 Level.WARNING,
83 "Unexpected exception from downstream.",
84 e.getCause());
85 e.getChannel().close();
86 }
87 }