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.io.IOException;
23 import java.net.InetSocketAddress;
24 import java.util.concurrent.atomic.AtomicInteger;
25
26 import org.apache.mina.core.service.IoHandlerAdapter;
27 import org.apache.mina.core.session.IdleStatus;
28 import org.apache.mina.core.session.IoSession;
29 import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
30
31
32
33
34
35
36
37
38
39 public class UdpServer extends IoHandlerAdapter {
40
41 public static final int PORT = 18567;
42
43
44 public static final int MAX_RECEIVED = 100000;
45
46
47 private static long t0;
48
49
50 private AtomicInteger nbReceived = new AtomicInteger(0);
51
52
53
54
55 @Override
56 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
57 cause.printStackTrace();
58 session.closeNow();
59 }
60
61
62
63
64 @Override
65 public void messageReceived(IoSession session, Object message) throws Exception {
66
67 int nb = nbReceived.incrementAndGet();
68
69 if (nb == 1) {
70 t0 = System.currentTimeMillis();
71 }
72
73 if (nb == MAX_RECEIVED) {
74 long t1 = System.currentTimeMillis();
75 System.out.println("-------------> end " + (t1 - t0));
76 }
77
78 if (nb % 10000 == 0) {
79 System.out.println("Received " + nb + " messages");
80 }
81
82
83 session.write(message);
84 }
85
86
87
88
89 @Override
90 public void sessionClosed(IoSession session) throws Exception {
91 System.out.println("Session closed...");
92
93
94 System.out.println("Nb message received : " + nbReceived.get());
95 nbReceived.set(0);
96 }
97
98
99
100
101 @Override
102 public void sessionCreated(IoSession session) throws Exception {
103 System.out.println("Session created...");
104 }
105
106
107
108
109 @Override
110 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
111 System.out.println("Session idle...");
112 }
113
114
115
116
117 @Override
118 public void sessionOpened(IoSession session) throws Exception {
119 System.out.println("Session Opened...");
120 }
121
122
123
124
125
126
127 public UdpServer() throws IOException {
128 NioDatagramAcceptorNioDatagramAcceptor.html#NioDatagramAcceptor">NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
129 acceptor.setHandler(this);
130
131
132
133
134
135 acceptor.bind(new InetSocketAddress(PORT));
136
137 System.out.println("Server started...");
138 }
139
140
141
142
143
144
145
146 public static void main(String[] args) throws IOException {
147 new UdpServer();
148 }
149 }