查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
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.ChannelFuture;
20  import io.netty.channel.ChannelFutureListener;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.SimpleChannelInboundHandler;
23  
24  /**
25   * Handles a client-side channel.
26   */
27  public class DiscardClientHandler extends SimpleChannelInboundHandler<Object> {
28  
29      private ByteBuf 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.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);
38  
39          // Send the initial messages.
40          generateTraffic();
41      }
42  
43      @Override
44      public void channelInactive(ChannelHandlerContext ctx) {
45          content.release();
46      }
47  
48      @Override
49      public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
50          // Server is supposed to send nothing, but if it sends something, discard it.
51      }
52  
53      @Override
54      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
55          // Close the connection when an exception is raised.
56          cause.printStackTrace();
57          ctx.close();
58      }
59  
60      long counter;
61  
62      private void generateTraffic() {
63          // Flush the outbound buffer to the socket.
64          // Once flushed, generate the same amount of traffic again.
65          ctx.writeAndFlush(content.retainedDuplicate()).addListener(trafficGenerator);
66      }
67  
68      private final ChannelFutureListener trafficGenerator = new ChannelFutureListener() {
69          @Override
70          public void operationComplete(ChannelFuture future) {
71              if (future.isSuccess()) {
72                  generateTraffic();
73              } else {
74                  future.cause().printStackTrace();
75                  future.channel().close();
76              }
77          }
78      };
79  }