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.tcp;
21
22 import io.netty.bootstrap.Bootstrap;
23 import io.netty.buffer.ByteBuf;
24 import io.netty.channel.ChannelHandlerContext;
25 import io.netty.channel.ChannelInboundHandlerAdapter;
26 import io.netty.channel.ChannelInitializer;
27 import io.netty.channel.ChannelOption;
28 import io.netty.channel.EventLoopGroup;
29 import io.netty.channel.nio.NioEventLoopGroup;
30 import io.netty.channel.socket.SocketChannel;
31 import io.netty.channel.socket.nio.NioSocketChannel;
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 Netty4TcpBenchmarkClient implements BenchmarkClient {
44
45 private EventLoopGroup group = new NioEventLoopGroup();
46
47
48
49
50 public Netty4TcpBenchmarkClient() {
51 }
52
53
54
55
56 public void start(final int port, final CountDownLatch counter, final byte[] data) throws IOException {
57 Bootstrap bootstrap = new Bootstrap();
58 bootstrap.group(group);
59 bootstrap.option(ChannelOption.SO_SNDBUF, 64 * 1024);
60 bootstrap.option(ChannelOption.TCP_NODELAY, true);
61 bootstrap.channel(NioSocketChannel.class);
62 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
63
64 @Override
65 protected void initChannel(SocketChannel ch) throws Exception {
66 ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
67 private void sendMessage(ChannelHandlerContext ctx, byte[] data) {
68 ByteBuf buf = ctx.alloc().buffer(data.length);
69 buf.writeBytes(data);
70 ctx.writeAndFlush(buf);
71 }
72
73 @Override
74 public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
75 ByteBuf buf = (ByteBuf)message;
76 for(int i=0; i < buf.readableBytes();i++) {
77 counter.countDown();
78 if (counter.getCount() > 0) {
79 sendMessage(ctx, data);
80 } else {
81 ctx.channel().close();
82 }
83 }
84 buf.release();
85 }
86
87 @Override
88 public void channelActive(ChannelHandlerContext ctx) throws Exception {
89 sendMessage(ctx, data);
90 }
91 });
92 }
93
94 @Override
95 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
96 cause.printStackTrace();
97 ctx.close();
98 }
99 });
100 bootstrap.connect(new InetSocketAddress(port));
101 }
102
103
104
105
106 public void stop() throws IOException {
107 group.shutdownGracefully();
108 }
109 }