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 java.io.IOException;
23 import java.net.InetSocketAddress;
24 import java.util.concurrent.CountDownLatch;
25
26 import org.apache.mina.core.BenchmarkClient;
27 import org.jboss.netty.bootstrap.ClientBootstrap;
28 import org.jboss.netty.buffer.ChannelBuffer;
29 import org.jboss.netty.buffer.ChannelBuffers;
30 import org.jboss.netty.channel.ChannelFactory;
31 import org.jboss.netty.channel.ChannelHandlerContext;
32 import org.jboss.netty.channel.ChannelPipeline;
33 import org.jboss.netty.channel.ChannelPipelineFactory;
34 import org.jboss.netty.channel.ChannelStateEvent;
35 import org.jboss.netty.channel.Channels;
36 import org.jboss.netty.channel.MessageEvent;
37 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
38 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
39
40
41
42
43
44 public class Netty3TcpBenchmarkClient implements BenchmarkClient {
45
46 private ChannelFactory factory;
47
48
49
50
51 public Netty3TcpBenchmarkClient() {
52 }
53
54
55
56
57 public void start(final int port, final CountDownLatch counter, final byte[] data) throws IOException {
58 factory = new NioClientSocketChannelFactory();
59 ClientBootstrap bootstrap = new ClientBootstrap(factory);
60 bootstrap.setOption("sendBufferSize", 64 * 1024);
61 bootstrap.setOption("tcpNoDelay", true);
62 bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
63 public ChannelPipeline getPipeline() throws Exception {
64 return Channels.pipeline(new SimpleChannelUpstreamHandler() {
65 private void sendMessage(ChannelHandlerContext ctx, byte[] data) {
66 ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(data);
67 ctx.getChannel().write(buffer);
68 }
69
70 @Override
71 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
72 if (e.getMessage() instanceof ChannelBuffer) {
73 ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
74 for (int i = 0; i < buffer.readableBytes(); ++i) {
75 counter.countDown();
76 if (counter.getCount() > 0) {
77 sendMessage(ctx, data);
78 } else {
79 ctx.getChannel().close();
80 }
81 }
82 } else {
83 throw new IllegalArgumentException(e.getMessage().getClass().getName());
84 }
85 }
86
87 @Override
88 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
89 sendMessage(ctx, data);
90 }
91
92 });
93 }
94 });
95 bootstrap.connect(new InetSocketAddress(port));
96 }
97
98
99
100
101 public void stop() throws IOException {
102 factory.releaseExternalResources();
103 }
104 }