1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.transport.socket.nio.support;
21
22 import java.io.IOException;
23 import java.net.InetSocketAddress;
24 import java.net.SocketAddress;
25 import java.nio.channels.DatagramChannel;
26 import java.nio.channels.SelectionKey;
27 import java.nio.channels.Selector;
28 import java.util.Iterator;
29 import java.util.Set;
30
31 import org.apache.mina.common.ByteBuffer;
32 import org.apache.mina.common.ConnectFuture;
33 import org.apache.mina.common.ExceptionMonitor;
34 import org.apache.mina.common.IoConnector;
35 import org.apache.mina.common.IoHandler;
36 import org.apache.mina.common.IoServiceConfig;
37 import org.apache.mina.common.IoSession;
38 import org.apache.mina.common.IoSessionRecycler;
39 import org.apache.mina.common.IoFilter.WriteRequest;
40 import org.apache.mina.common.support.AbstractIoFilterChain;
41 import org.apache.mina.common.support.BaseIoConnector;
42 import org.apache.mina.common.support.DefaultConnectFuture;
43 import org.apache.mina.transport.socket.nio.DatagramConnectorConfig;
44 import org.apache.mina.transport.socket.nio.DatagramServiceConfig;
45 import org.apache.mina.transport.socket.nio.DatagramSessionConfig;
46 import org.apache.mina.util.NamePreservingRunnable;
47 import org.apache.mina.util.Queue;
48
49 import edu.emory.mathcs.backport.java.util.concurrent.Executor;
50
51
52
53
54
55
56
57 public class DatagramConnectorDelegate extends BaseIoConnector implements
58 DatagramService {
59 private static volatile int nextId = 0;
60
61 private final IoConnector wrapper;
62
63 private final Executor executor;
64
65 private final int id = nextId++;
66
67 private Selector selector;
68
69 private DatagramConnectorConfig defaultConfig = new DatagramConnectorConfig();
70
71 private final Queue registerQueue = new Queue();
72
73 private final Queue cancelQueue = new Queue();
74
75 private final Queue flushingSessions = new Queue();
76
77 private final Queue trafficControllingSessions = new Queue();
78
79 private Worker worker;
80
81
82
83
84 public DatagramConnectorDelegate(IoConnector wrapper, Executor executor) {
85 this.wrapper = wrapper;
86 this.executor = executor;
87 }
88
89 public ConnectFuture connect(SocketAddress address, IoHandler handler,
90 IoServiceConfig config) {
91 return connect(address, null, handler, config);
92 }
93
94 public ConnectFuture connect(SocketAddress address,
95 SocketAddress localAddress, IoHandler handler,
96 IoServiceConfig config) {
97 if (address == null)
98 throw new NullPointerException("address");
99 if (handler == null)
100 throw new NullPointerException("handler");
101
102 if (!(address instanceof InetSocketAddress))
103 throw new IllegalArgumentException("Unexpected address type: "
104 + address.getClass());
105
106 if (localAddress != null
107 && !(localAddress instanceof InetSocketAddress)) {
108 throw new IllegalArgumentException(
109 "Unexpected local address type: " + localAddress.getClass());
110 }
111
112 if (config == null) {
113 config = getDefaultConfig();
114 }
115
116 DatagramChannel ch = null;
117 boolean initialized = false;
118 try {
119 ch = DatagramChannel.open();
120 DatagramSessionConfig cfg;
121 if (config.getSessionConfig() instanceof DatagramSessionConfig) {
122 cfg = (DatagramSessionConfig) config.getSessionConfig();
123 } else {
124 cfg = (DatagramSessionConfig) getDefaultConfig()
125 .getSessionConfig();
126 }
127
128 ch.socket().setReuseAddress(cfg.isReuseAddress());
129 ch.socket().setBroadcast(cfg.isBroadcast());
130 ch.socket().setReceiveBufferSize(cfg.getReceiveBufferSize());
131 ch.socket().setSendBufferSize(cfg.getSendBufferSize());
132
133 if (ch.socket().getTrafficClass() != cfg.getTrafficClass()) {
134 ch.socket().setTrafficClass(cfg.getTrafficClass());
135 }
136
137 if (localAddress != null) {
138 ch.socket().bind(localAddress);
139 }
140 ch.connect(address);
141 ch.configureBlocking(false);
142 initialized = true;
143 } catch (IOException e) {
144 return DefaultConnectFuture.newFailedFuture(e);
145 } finally {
146 if (!initialized && ch != null) {
147 try {
148 ch.disconnect();
149 ch.close();
150 } catch (IOException e) {
151 ExceptionMonitor.getInstance().exceptionCaught(e);
152 }
153 }
154 }
155
156 RegistrationRequest request = new RegistrationRequest(ch, handler,
157 config);
158 synchronized (this) {
159 try {
160 startupWorker();
161 } catch (IOException e) {
162 try {
163 ch.disconnect();
164 ch.close();
165 } catch (IOException e2) {
166 ExceptionMonitor.getInstance().exceptionCaught(e2);
167 }
168
169 return DefaultConnectFuture.newFailedFuture(e);
170 }
171
172 synchronized (registerQueue) {
173 registerQueue.push(request);
174 }
175 selector.wakeup();
176 }
177
178 return request;
179 }
180
181 public IoServiceConfig getDefaultConfig() {
182 return defaultConfig;
183 }
184
185
186
187
188
189
190
191 public void setDefaultConfig(DatagramConnectorConfig defaultConfig) {
192 if (defaultConfig == null) {
193 throw new NullPointerException("defaultConfig");
194 }
195 this.defaultConfig = defaultConfig;
196 }
197
198 private synchronized Selector getSelector() {
199 return this.selector;
200 }
201
202 private synchronized void startupWorker() throws IOException {
203 if (worker == null) {
204 selector = Selector.open();
205 worker = new Worker();
206 executor.execute(new NamePreservingRunnable(worker));
207 }
208 }
209
210 public void closeSession(DatagramSessionImpl session) {
211 synchronized (this) {
212 try {
213 startupWorker();
214 } catch (IOException e) {
215
216
217
218
219
220 return;
221 }
222
223 synchronized (cancelQueue) {
224 cancelQueue.push(session);
225 }
226
227 selector.wakeup();
228 }
229 }
230
231 public void flushSession(DatagramSessionImpl session) {
232 scheduleFlush(session);
233 Selector selector = getSelector();
234 if (selector != null) {
235 selector.wakeup();
236 }
237 }
238
239 private void scheduleFlush(DatagramSessionImpl session) {
240 synchronized (flushingSessions) {
241 flushingSessions.push(session);
242 }
243 }
244
245 public void updateTrafficMask(DatagramSessionImpl session) {
246 scheduleTrafficControl(session);
247 Selector selector = getSelector();
248 if (selector != null) {
249 selector.wakeup();
250 }
251 }
252
253 private void scheduleTrafficControl(DatagramSessionImpl session) {
254 synchronized (trafficControllingSessions) {
255 trafficControllingSessions.push(session);
256 }
257 }
258
259 private void doUpdateTrafficMask() {
260 if (trafficControllingSessions.isEmpty())
261 return;
262
263 for (;;) {
264 DatagramSessionImpl session;
265
266 synchronized (trafficControllingSessions) {
267 session = (DatagramSessionImpl) trafficControllingSessions
268 .pop();
269 }
270
271 if (session == null)
272 break;
273
274 SelectionKey key = session.getSelectionKey();
275
276
277
278 if (key == null) {
279 scheduleTrafficControl(session);
280 break;
281 }
282
283 if (!key.isValid()) {
284 continue;
285 }
286
287
288
289 int ops = SelectionKey.OP_READ;
290 Queue writeRequestQueue = session.getWriteRequestQueue();
291 synchronized (writeRequestQueue) {
292 if (!writeRequestQueue.isEmpty()) {
293 ops |= SelectionKey.OP_WRITE;
294 }
295 }
296
297
298 int mask = session.getTrafficMask().getInterestOps();
299 key.interestOps(ops & mask);
300 }
301 }
302
303 private class Worker implements Runnable {
304 public void run() {
305 Thread.currentThread().setName("DatagramConnector-" + id);
306
307 Selector selector = getSelector();
308 for (;;) {
309 try {
310 int nKeys = selector.select();
311
312 registerNew();
313 doUpdateTrafficMask();
314
315 if (nKeys > 0) {
316 processReadySessions(selector.selectedKeys());
317 }
318
319 flushSessions();
320 cancelKeys();
321
322 if (selector.keys().isEmpty()) {
323 synchronized (DatagramConnectorDelegate.this) {
324 if (selector.keys().isEmpty()
325 && registerQueue.isEmpty()
326 && cancelQueue.isEmpty()) {
327 worker = null;
328 try {
329 selector.close();
330 } catch (IOException e) {
331 ExceptionMonitor.getInstance()
332 .exceptionCaught(e);
333 } finally {
334 DatagramConnectorDelegate.this.selector = null;
335 }
336 break;
337 }
338 }
339 }
340 } catch (IOException e) {
341 ExceptionMonitor.getInstance().exceptionCaught(e);
342
343 try {
344 Thread.sleep(1000);
345 } catch (InterruptedException e1) {
346 }
347 }
348 }
349 }
350 }
351
352 private void processReadySessions(Set keys) {
353 Iterator it = keys.iterator();
354 while (it.hasNext()) {
355 SelectionKey key = (SelectionKey) it.next();
356 it.remove();
357
358 DatagramSessionImpl session = (DatagramSessionImpl) key
359 .attachment();
360
361
362 getSessionRecycler(session).recycle(session.getLocalAddress(),
363 session.getRemoteAddress());
364
365 if (key.isReadable() && session.getTrafficMask().isReadable()) {
366 readSession(session);
367 }
368
369 if (key.isWritable() && session.getTrafficMask().isWritable()) {
370 scheduleFlush(session);
371 }
372 }
373 }
374
375 private IoSessionRecycler getSessionRecycler(IoSession session) {
376 IoServiceConfig config = session.getServiceConfig();
377 IoSessionRecycler sessionRecycler;
378 if (config instanceof DatagramServiceConfig) {
379 sessionRecycler = ((DatagramServiceConfig) config)
380 .getSessionRecycler();
381 } else {
382 sessionRecycler = defaultConfig.getSessionRecycler();
383 }
384 return sessionRecycler;
385 }
386
387 private void readSession(DatagramSessionImpl session) {
388
389 ByteBuffer readBuf = ByteBuffer.allocate(session.getReadBufferSize());
390 try {
391 int readBytes = session.getChannel().read(readBuf.buf());
392 if (readBytes > 0) {
393 readBuf.flip();
394 ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit());
395 newBuf.put(readBuf);
396 newBuf.flip();
397
398 session.increaseReadBytes(readBytes);
399 session.getFilterChain().fireMessageReceived(session, newBuf);
400 }
401 } catch (IOException e) {
402 session.getFilterChain().fireExceptionCaught(session, e);
403 } finally {
404 readBuf.release();
405 }
406 }
407
408 private void flushSessions() {
409 if (flushingSessions.size() == 0)
410 return;
411
412 for (;;) {
413 DatagramSessionImpl session;
414
415 synchronized (flushingSessions) {
416 session = (DatagramSessionImpl) flushingSessions.pop();
417 }
418
419 if (session == null)
420 break;
421
422 try {
423 flush(session);
424 } catch (IOException e) {
425 session.getFilterChain().fireExceptionCaught(session, e);
426 }
427 }
428 }
429
430 private void flush(DatagramSessionImpl session) throws IOException {
431 DatagramChannel ch = session.getChannel();
432
433 Queue writeRequestQueue = session.getWriteRequestQueue();
434
435 WriteRequest req;
436 for (;;) {
437 synchronized (writeRequestQueue) {
438 req = (WriteRequest) writeRequestQueue.first();
439 }
440
441 if (req == null)
442 break;
443
444 ByteBuffer buf = (ByteBuffer) req.getMessage();
445 if (buf.remaining() == 0) {
446
447 synchronized (writeRequestQueue) {
448 writeRequestQueue.pop();
449 }
450
451 session.increaseWrittenMessages();
452 buf.reset();
453 session.getFilterChain().fireMessageSent(session, req);
454 continue;
455 }
456
457 SelectionKey key = session.getSelectionKey();
458 if (key == null) {
459 scheduleFlush(session);
460 break;
461 }
462 if (!key.isValid()) {
463 continue;
464 }
465
466 int writtenBytes = ch.write(buf.buf());
467
468 if (writtenBytes == 0) {
469
470 key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
471 } else if (writtenBytes > 0) {
472 key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
473
474
475 synchronized (writeRequestQueue) {
476 writeRequestQueue.pop();
477 }
478
479 session.increaseWrittenBytes(writtenBytes);
480 session.increaseWrittenMessages();
481 buf.reset();
482 session.getFilterChain().fireMessageSent(session, req);
483 }
484 }
485 }
486
487 private void registerNew() {
488 if (registerQueue.isEmpty())
489 return;
490
491 Selector selector = getSelector();
492 for (;;) {
493 RegistrationRequest req;
494 synchronized (registerQueue) {
495 req = (RegistrationRequest) registerQueue.pop();
496 }
497
498 if (req == null)
499 break;
500
501 DatagramSessionImpl session = new DatagramSessionImpl(wrapper,
502 this, req.config, req.channel, req.handler, req.channel
503 .socket().getRemoteSocketAddress(), req.channel
504 .socket().getLocalSocketAddress());
505
506
507 session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE, req);
508
509 boolean success = false;
510 try {
511 SelectionKey key = req.channel.register(selector,
512 SelectionKey.OP_READ, session);
513
514 session.setSelectionKey(key);
515 buildFilterChain(req, session);
516 getSessionRecycler(session).put(session);
517
518
519 getListeners().fireSessionCreated(session);
520 success = true;
521 } catch (Throwable t) {
522
523 session.getFilterChain().fireExceptionCaught(session, t);
524 } finally {
525 if (!success) {
526 try {
527 req.channel.disconnect();
528 req.channel.close();
529 } catch (IOException e) {
530 ExceptionMonitor.getInstance().exceptionCaught(e);
531 }
532 }
533 }
534 }
535 }
536
537 private void buildFilterChain(RegistrationRequest req, IoSession session)
538 throws Exception {
539 getFilterChainBuilder().buildFilterChain(session.getFilterChain());
540 req.config.getFilterChainBuilder().buildFilterChain(
541 session.getFilterChain());
542 req.config.getThreadModel().buildFilterChain(session.getFilterChain());
543 }
544
545 private void cancelKeys() {
546 if (cancelQueue.isEmpty())
547 return;
548
549 Selector selector = getSelector();
550 for (;;) {
551 DatagramSessionImpl session;
552 synchronized (cancelQueue) {
553 session = (DatagramSessionImpl) cancelQueue.pop();
554 }
555
556 if (session == null)
557 break;
558 else {
559 SelectionKey key = session.getSelectionKey();
560 DatagramChannel ch = (DatagramChannel) key.channel();
561 try {
562 ch.disconnect();
563 ch.close();
564 } catch (IOException e) {
565 ExceptionMonitor.getInstance().exceptionCaught(e);
566 }
567
568 getListeners().fireSessionDestroyed(session);
569 session.getCloseFuture().setClosed();
570 key.cancel();
571 selector.wakeup();
572 }
573 }
574 }
575
576 private static class RegistrationRequest extends DefaultConnectFuture {
577 private final DatagramChannel channel;
578
579 private final IoHandler handler;
580
581 private final IoServiceConfig config;
582
583 private RegistrationRequest(DatagramChannel channel, IoHandler handler,
584 IoServiceConfig config) {
585 this.channel = channel;
586 this.handler = handler;
587 this.config = config;
588 }
589 }
590 }