View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Handler implementation for the echo client.  It initiates the ping-pong
30   * traffic between the echo client and server by sending the first message to
31   * the server.
32   */
33  public class EchoClientHandler extends SimpleChannelUpstreamHandler {
34  
35      private final ChannelBuffer firstMessage;
36      private final AtomicLong transferredBytes = new AtomicLong();
37  
38      /**
39       * Creates a client-side handler.
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          // Send the first message.  Server will not send anything here
55          // because the firstMessage's capacity is 0.
56          e.getChannel().write(firstMessage);
57      }
58  
59      @Override
60      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
61          // Send back the received message to the remote peer.
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          // Close the connection when an exception is raised.
69          e.getCause().printStackTrace();
70          e.getChannel().close();
71      }
72  }