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