1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.core.nio.udp;
21
22 import io.netty.bootstrap.Bootstrap;
23 import io.netty.buffer.ByteBuf;
24 import io.netty.channel.ChannelHandlerContext;
25 import io.netty.channel.ChannelInitializer;
26 import io.netty.channel.ChannelOption;
27 import io.netty.channel.SimpleChannelInboundHandler;
28 import io.netty.channel.nio.NioEventLoopGroup;
29 import io.netty.channel.socket.DatagramChannel;
30 import io.netty.channel.socket.DatagramPacket;
31 import io.netty.channel.socket.nio.NioDatagramChannel;
32
33 import java.io.IOException;
34 import java.net.InetSocketAddress;
35 import java.util.concurrent.CountDownLatch;
36
37 import org.apache.mina.core.BenchmarkClient;
38
39
40
41
42
43 public class Netty4UdpBenchmarkClient implements BenchmarkClient {
44
45 private Bootstrap bootstrap;
46
47
48
49
50 public Netty4UdpBenchmarkClient() {
51 }
52
53
54
55
56 public void start(final int port, final CountDownLatch counter, final byte[] data) throws IOException {
57 bootstrap = new Bootstrap();
58 bootstrap.option(ChannelOption.SO_SNDBUF, 65536);
59 bootstrap.group(new NioEventLoopGroup());
60 bootstrap.channel(NioDatagramChannel.class);
61 bootstrap.handler(new ChannelInitializer<DatagramChannel>() {
62
63 @Override
64 protected void initChannel(DatagramChannel ch) throws Exception {
65 ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
66 private void sendMessage(ChannelHandlerContext ctx, byte[] data, InetSocketAddress address) {
67 ByteBuf buf = ctx.alloc().buffer(data.length);
68 buf.writeBytes(data);
69 ctx.writeAndFlush(new DatagramPacket(buf, address));
70 }
71
72 @Override
73 public void channelActive(ChannelHandlerContext ctx) throws Exception {
74 sendMessage(ctx, data, new InetSocketAddress("localhost", port));
75 }
76
77 @Override
78 protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket message) throws Exception {
79 for(int i=0; i < message.content().readableBytes();i++) {
80 counter.countDown();
81 if (counter.getCount() > 0) {
82 sendMessage(ctx, data, message.sender());
83 } else {
84 ctx.channel().close();
85 }
86 }
87 }
88 });
89 }
90 });
91 bootstrap.bind(port+1);
92 }
93
94
95
96
97 public void stop() throws IOException {
98 bootstrap.group().shutdownGracefully();
99 }
100 }