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