1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.udp.perf;
21
22 import java.net.InetSocketAddress;
23
24 import org.apache.mina.core.buffer.IoBuffer;
25 import org.apache.mina.core.future.ConnectFuture;
26 import org.apache.mina.core.service.IoConnector;
27 import org.apache.mina.core.service.IoHandlerAdapter;
28 import org.apache.mina.core.session.IdleStatus;
29 import org.apache.mina.core.session.IoSession;
30 import org.apache.mina.transport.socket.DatagramSessionConfig;
31 import org.apache.mina.transport.socket.nio.NioDatagramConnector;
32
33
34
35
36
37
38
39
40
41 public class UdpClient extends IoHandlerAdapter {
42
43 private IoConnector connector;
44
45
46 private static IoSession session;
47
48
49
50
51 public UdpClient() {
52 connector = new NioDatagramConnector();
53
54 connector.setHandler(this);
55 DatagramSessionConfig dcfg = (DatagramSessionConfig) connector.getSessionConfig();
56
57 ConnectFuture connFuture = connector.connect(new InetSocketAddress("localhost", UdpServer.PORT));
58
59 connFuture.awaitUninterruptibly();
60
61 session = connFuture.getSession();
62 }
63
64
65
66
67 @Override
68 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
69 cause.printStackTrace();
70 }
71
72
73
74
75 @Override
76 public void messageReceived(IoSession session, Object message) throws Exception {
77 }
78
79
80
81
82 @Override
83 public void messageSent(IoSession session, Object message) throws Exception {
84 }
85
86
87
88
89 @Override
90 public void sessionClosed(IoSession session) throws Exception {
91 }
92
93
94
95
96 @Override
97 public void sessionCreated(IoSession session) throws Exception {
98 }
99
100
101
102
103 @Override
104 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
105 }
106
107
108
109
110 @Override
111 public void sessionOpened(IoSession session) throws Exception {
112 }
113
114
115
116
117
118
119
120 public static void main(String[] args) throws Exception {
121 UdpClient client = new UdpClient();
122
123 long t0 = System.currentTimeMillis();
124
125 for (int i = 0; i <= UdpServer.MAX_RECEIVED; i++) {
126
127 Thread.sleep(1);
128
129
130 String str = Integer.toString(i);
131 byte[] data = str.getBytes();
132 IoBuffer buffer = IoBuffer.allocate(data.length);
133 buffer.put(data);
134 buffer.flip();
135 session.write(buffer);
136
137 if (i % 10000 == 0) {
138 System.out.println("Sent " + i + " messages");
139 }
140 }
141
142 long t1 = System.currentTimeMillis();
143
144 System.out.println("Sent messages delay : " + (t1 - t0));
145
146 Thread.sleep(100000);
147
148 client.connector.dispose(true);
149 }
150 }