1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
37 content = ctx.bufferAllocator()
38 .allocate(DiscardClient.SIZE)
39 .writerOffset(DiscardClient.SIZE)
40 .fill((byte) 0)
41 .makeReadOnly();
42
43
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
55 }
56
57 @Override
58 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
59
60 cause.printStackTrace();
61 ctx.close();
62 }
63
64 private void generateTraffic() {
65
66
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 }