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.discard;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.ChannelFutureListener;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.SimpleChannelInboundHandler;
22  
23  /**
24   * Handles a client-side channel.
25   */
26  public class DiscardClientHandler extends SimpleChannelInboundHandler<Object> {
27  
28      private ByteBuf content;
29      private ChannelHandlerContext ctx;
30  
31      @Override
32      public void channelActive(ChannelHandlerContext ctx) {
33          this.ctx = ctx;
34  
35          // Initialize the message.
36          content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);
37  
38          // Send the initial messages.
39          generateTraffic();
40      }
41  
42      @Override
43      public void channelInactive(ChannelHandlerContext ctx) {
44          content.release();
45      }
46  
47      @Override
48      public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
49          // Server is supposed to send nothing, but if it sends something, discard it.
50      }
51  
52      @Override
53      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
54          // Close the connection when an exception is raised.
55          cause.printStackTrace();
56          ctx.close();
57      }
58  
59      long counter;
60  
61      private void generateTraffic() {
62          // Flush the outbound buffer to the socket.
63          // Once flushed, generate the same amount of traffic again.
64          ctx.writeAndFlush(content.retainedDuplicate()).addListener(trafficGenerator);
65      }
66  
67      private final ChannelFutureListener trafficGenerator = future -> {
68          if (future.isSuccess()) {
69              generateTraffic();
70          } else {
71              future.cause().printStackTrace();
72              future.channel().close();
73          }
74      };
75  }