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 org.jboss.netty.buffer.ChannelBuffer;
19 import org.jboss.netty.buffer.ChannelBuffers;
20 import org.jboss.netty.channel.ChannelHandlerContext;
21 import org.jboss.netty.channel.ChannelStateEvent;
22 import org.jboss.netty.channel.ExceptionEvent;
23 import org.jboss.netty.channel.MessageEvent;
24 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
25
26 import java.util.concurrent.atomic.AtomicLong;
27
28
29
30
31
32
33 public class EchoClientHandler extends SimpleChannelUpstreamHandler {
34
35 private final ChannelBuffer firstMessage;
36 private final AtomicLong transferredBytes = new AtomicLong();
37
38
39
40
41 public EchoClientHandler() {
42 firstMessage = ChannelBuffers.buffer(EchoClient.SIZE);
43 for (int i = 0; i < firstMessage.capacity(); i ++) {
44 firstMessage.writeByte((byte) i);
45 }
46 }
47
48 public long getTransferredBytes() {
49 return transferredBytes.get();
50 }
51
52 @Override
53 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
54
55
56 e.getChannel().write(firstMessage);
57 }
58
59 @Override
60 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
61
62 transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
63 e.getChannel().write(e.getMessage());
64 }
65
66 @Override
67 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
68
69 e.getCause().printStackTrace();
70 e.getChannel().close();
71 }
72 }