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    *   https://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 io.netty.example.objectecho;
17  
18  import io.netty.channel.ChannelFuture;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.channel.ChannelInboundHandlerAdapter;
21  
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import static io.netty.channel.ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE;
26  
27  /**
28   * Handler implementation for the object echo client.  It initiates the
29   * ping-pong traffic between the object echo client and server by sending the
30   * first message to the server.
31   */
32  public class ObjectEchoClientHandler extends ChannelInboundHandlerAdapter {
33  
34      private final List<Integer> firstMessage;
35  
36      /**
37       * Creates a client-side handler.
38       */
39      public ObjectEchoClientHandler() {
40          firstMessage = new ArrayList<Integer>(ObjectEchoClient.SIZE);
41          for (int i = 0; i < ObjectEchoClient.SIZE; i ++) {
42              firstMessage.add(Integer.valueOf(i));
43          }
44      }
45  
46      @Override
47      public void channelActive(ChannelHandlerContext ctx) {
48          // Send the first message if this handler is a client-side handler.
49          ChannelFuture future = ctx.writeAndFlush(firstMessage);
50          future.addListener(FIRE_EXCEPTION_ON_FAILURE); // Let object serialisation exceptions propagate.
51      }
52  
53      @Override
54      public void channelRead(ChannelHandlerContext ctx, Object msg) {
55          // Echo back the received object to the server.
56          ctx.write(msg);
57      }
58  
59      @Override
60      public void channelReadComplete(ChannelHandlerContext ctx) {
61          ctx.flush();
62      }
63  
64      @Override
65      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
66          cause.printStackTrace();
67          ctx.close();
68      }
69  }