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