sonixlabs-eventmachine-java 1.0.0.rc.5-java → 1.0.0.rc.7-java

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,29 +1,29 @@
1
1
  /**
2
2
  * $Id$
3
- *
3
+ *
4
4
  * Author:: Francis Cianfrocca (gmail: blackhedd)
5
5
  * Homepage:: http://rubyeventmachine.com
6
6
  * Date:: 15 Jul 2007
7
- *
7
+ *
8
8
  * See EventMachine and EventMachine::Connection for documentation and
9
9
  * usage examples.
10
- *
10
+ *
11
11
  *
12
12
  *----------------------------------------------------------------------------
13
13
  *
14
14
  * Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
15
15
  * Gmail: blackhedd
16
- *
16
+ *
17
17
  * This program is free software; you can redistribute it and/or modify
18
18
  * it under the terms of either: 1) the GNU General Public License
19
19
  * as published by the Free Software Foundation; either version 2 of the
20
20
  * License, or (at your option) any later version; or 2) Ruby's License.
21
- *
21
+ *
22
22
  * See the file COPYING for complete licensing information.
23
23
  *
24
24
  *---------------------------------------------------------------------------
25
25
  *
26
- *
26
+ *
27
27
  */
28
28
 
29
29
  package com.rubyeventmachine;
@@ -38,551 +38,551 @@ import java.security.*;
38
38
  import java.lang.reflect.UndeclaredThrowableException;
39
39
 
40
40
  public class EmReactor {
41
- public final int EM_TIMER_FIRED = 100;
42
- public final int EM_CONNECTION_READ = 101;
43
- public final int EM_CONNECTION_UNBOUND = 102;
44
- public final int EM_CONNECTION_ACCEPTED = 103;
45
- public final int EM_CONNECTION_COMPLETED = 104;
46
- public final int EM_LOOPBREAK_SIGNAL = 105;
47
- public final int EM_CONNECTION_NOTIFY_READABLE = 106;
48
- public final int EM_CONNECTION_NOTIFY_WRITABLE = 107;
49
- public final int EM_SSL_HANDSHAKE_COMPLETED = 108;
50
- public final int EM_SSL_VERIFY = 109;
51
- public final int EM_PROXY_TARGET_UNBOUND = 110;
52
- public final int EM_PROXY_COMPLETED = 111;
53
-
54
- private Selector mySelector;
55
- private TreeMap<Long, ArrayList<Long>> Timers;
56
- private HashMap<Long, EventableChannel> Connections;
57
- private HashMap<Long, ServerSocketChannel> Acceptors;
58
- private ArrayList<Long> NewConnections;
59
- private ArrayList<Long> UnboundConnections;
60
- private ArrayList<EventableSocketChannel> DetachedConnections;
61
-
62
- private boolean bRunReactor;
63
- private long BindingIndex;
64
- private AtomicBoolean loopBreaker;
65
- private ByteBuffer myReadBuffer;
66
- private int timerQuantum;
67
-
68
- public EmReactor() {
69
- Timers = new TreeMap<Long, ArrayList<Long>>();
70
- Connections = new HashMap<Long, EventableChannel>();
71
- Acceptors = new HashMap<Long, ServerSocketChannel>();
72
- NewConnections = new ArrayList<Long>();
73
- UnboundConnections = new ArrayList<Long>();
74
- DetachedConnections = new ArrayList<EventableSocketChannel>();
75
-
76
- BindingIndex = 0;
77
- loopBreaker = new AtomicBoolean();
78
- loopBreaker.set(false);
79
- myReadBuffer = ByteBuffer.allocate(32*1024); // don't use a direct buffer. Ruby doesn't seem to like them.
80
- timerQuantum = 98;
81
- }
82
-
83
- /**
84
- * This is a no-op stub, intended to be overridden in user code.
85
- */
86
- public void eventCallback (long sig, int eventType, ByteBuffer data, long data2) {
87
- System.out.println ("Default callback: "+sig+" "+eventType+" "+data+" "+data2);
88
- }
89
- public void eventCallback (long sig, int eventType, ByteBuffer data) {
90
- eventCallback (sig, eventType, data, 0);
91
- }
92
-
93
-
94
- public void run() {
95
- try {
96
- mySelector = Selector.open();
97
- bRunReactor = true;
98
- } catch (IOException e) {
99
- throw new RuntimeException ("Could not open selector", e);
100
- }
101
-
102
- while (bRunReactor) {
103
- runLoopbreaks();
104
- if (!bRunReactor) break;
105
-
106
- runTimers();
107
- if (!bRunReactor) break;
108
-
109
- removeUnboundConnections();
110
- checkIO();
111
- addNewConnections();
112
- processIO();
113
- }
114
-
115
- close();
116
- }
117
-
118
- void addNewConnections() {
119
- ListIterator<EventableSocketChannel> iter = DetachedConnections.listIterator(0);
120
- while (iter.hasNext()) {
121
- EventableSocketChannel ec = iter.next();
122
- ec.cleanup();
123
- }
124
- DetachedConnections.clear();
125
-
126
- ListIterator<Long> iter2 = NewConnections.listIterator(0);
127
- while (iter2.hasNext()) {
128
- long b = iter2.next();
129
-
130
- EventableChannel ec = Connections.get(b);
131
- if (ec != null) {
132
- try {
133
- ec.register();
134
- } catch (ClosedChannelException e) {
135
- UnboundConnections.add (ec.getBinding());
136
- }
137
- }
138
- }
139
- NewConnections.clear();
140
- }
141
-
142
- void removeUnboundConnections() {
143
- ListIterator<Long> iter = UnboundConnections.listIterator(0);
144
- while (iter.hasNext()) {
145
- long b = iter.next();
146
-
147
- EventableChannel ec = Connections.remove(b);
148
- if (ec != null) {
149
- eventCallback (b, EM_CONNECTION_UNBOUND, null);
150
- ec.close();
151
-
152
- EventableSocketChannel sc = (EventableSocketChannel) ec;
153
- if (sc != null && sc.isAttached())
154
- DetachedConnections.add (sc);
155
- }
156
- }
157
- UnboundConnections.clear();
158
- }
159
-
160
- void checkIO() {
161
- long timeout;
162
-
163
- if (NewConnections.size() > 0) {
164
- timeout = -1;
165
- } else if (!Timers.isEmpty()) {
166
- long now = new Date().getTime();
167
- long k = Timers.firstKey();
168
- long diff = k-now;
169
-
170
- if (diff <= 0)
171
- timeout = -1; // don't wait, just poll once
172
- else
173
- timeout = diff;
174
- } else {
175
- timeout = 0; // wait indefinitely
176
- }
177
-
178
- try {
179
- if (timeout == -1)
180
- mySelector.selectNow();
181
- else
182
- mySelector.select(timeout);
183
- } catch (IOException e) {
184
- e.printStackTrace();
185
- }
186
- }
187
-
188
- void processIO() {
189
- Iterator<SelectionKey> it = mySelector.selectedKeys().iterator();
190
- while (it.hasNext()) {
191
- SelectionKey k = it.next();
192
- it.remove();
193
-
194
- if (k.isConnectable())
195
- isConnectable(k);
196
-
197
- else if (k.isAcceptable())
198
- isAcceptable(k);
199
-
200
- else {
201
- if (k.isWritable())
202
- isWritable(k);
203
-
204
- if (k.isReadable())
205
- isReadable(k);
206
- }
207
- }
208
- }
209
-
210
- void isAcceptable (SelectionKey k) {
211
- ServerSocketChannel ss = (ServerSocketChannel) k.channel();
212
- SocketChannel sn;
213
- long b;
214
-
215
- for (int n = 0; n < 10; n++) {
216
- try {
217
- sn = ss.accept();
218
- if (sn == null)
219
- break;
220
- } catch (IOException e) {
221
- e.printStackTrace();
222
- k.cancel();
223
-
224
- ServerSocketChannel server = Acceptors.remove(k.attachment());
225
- if (server != null)
226
- try{ server.close(); } catch (IOException ex) {};
227
- break;
228
- }
229
-
230
- try {
231
- sn.configureBlocking(false);
232
- } catch (IOException e) {
233
- e.printStackTrace();
234
- continue;
235
- }
236
-
237
- b = createBinding();
238
- EventableSocketChannel ec = new EventableSocketChannel (sn, b, mySelector);
239
- Connections.put (b, ec);
240
- NewConnections.add (b);
241
-
242
- eventCallback (((Long)k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b);
243
- }
244
- }
245
-
246
- void isReadable (SelectionKey k) {
247
- EventableChannel ec = (EventableChannel) k.attachment();
248
- long b = ec.getBinding();
249
-
250
- if (ec.isWatchOnly()) {
251
- if (ec.isNotifyReadable())
252
- eventCallback (b, EM_CONNECTION_NOTIFY_READABLE, null);
253
- } else {
254
- myReadBuffer.clear();
255
-
256
- try {
257
- ec.readInboundData (myReadBuffer);
258
- myReadBuffer.flip();
259
- if (myReadBuffer.limit() > 0)
260
- eventCallback (b, EM_CONNECTION_READ, myReadBuffer);
261
- } catch (IOException e) {
262
- UnboundConnections.add (b);
263
- }
264
- }
265
- }
266
-
267
- void isWritable (SelectionKey k) {
268
- EventableChannel ec = (EventableChannel) k.attachment();
269
- long b = ec.getBinding();
270
-
271
- if (ec.isWatchOnly()) {
272
- if (ec.isNotifyWritable())
273
- eventCallback (b, EM_CONNECTION_NOTIFY_WRITABLE, null);
274
- }
275
- else {
276
- try {
277
- if (!ec.writeOutboundData())
278
- UnboundConnections.add (b);
279
- } catch (IOException e) {
280
- UnboundConnections.add (b);
281
- }
282
- }
283
- }
284
-
285
- void isConnectable (SelectionKey k) {
286
- EventableSocketChannel ec = (EventableSocketChannel) k.attachment();
287
- long b = ec.getBinding();
288
-
289
- try {
290
- if (ec.finishConnecting())
291
- eventCallback (b, EM_CONNECTION_COMPLETED, null);
292
- else
293
- UnboundConnections.add (b);
294
- } catch (IOException e) {
295
- UnboundConnections.add (b);
296
- }
297
- }
298
-
299
- void close() {
300
- try {
301
- if (mySelector != null)
302
- mySelector.close();
303
- } catch (IOException e) {}
304
- mySelector = null;
305
-
306
- // run down open connections and sockets.
307
- Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
308
- while (i.hasNext()) {
309
- try {
310
- i.next().close();
311
- } catch (IOException e) {}
312
- }
313
-
314
- // 29Sep09: We create an ArrayList of the existing connections, then iterate over
315
- // that to call unbind on them. This is because an unbind can trigger a reconnect,
316
- // which will add to the Connections HashMap, causing a ConcurrentModificationException.
317
- // XXX: The correct behavior here would be to latch the various reactor methods to return
318
- // immediately if the reactor is shutting down.
319
- ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
320
- Iterator<EventableChannel> i2 = Connections.values().iterator();
321
- while (i2.hasNext()) {
322
- EventableChannel ec = i2.next();
323
- if (ec != null) {
324
- conns.add (ec);
325
- }
326
- }
327
- Connections.clear();
328
-
329
- ListIterator<EventableChannel> i3 = conns.listIterator(0);
330
- while (i3.hasNext()) {
331
- EventableChannel ec = i3.next();
332
- eventCallback (ec.getBinding(), EM_CONNECTION_UNBOUND, null);
333
- ec.close();
334
-
335
- EventableSocketChannel sc = (EventableSocketChannel) ec;
336
- if (sc != null && sc.isAttached())
337
- DetachedConnections.add (sc);
338
- }
339
-
340
- ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
341
- while (i4.hasNext()) {
342
- EventableSocketChannel ec = i4.next();
343
- ec.cleanup();
344
- }
345
- DetachedConnections.clear();
346
- }
347
-
348
- void runLoopbreaks() {
349
- if (loopBreaker.getAndSet(false)) {
350
- eventCallback (0, EM_LOOPBREAK_SIGNAL, null);
351
- }
352
- }
353
-
354
- public void stop() {
355
- bRunReactor = false;
356
- signalLoopbreak();
357
- }
358
-
359
- void runTimers() {
360
- long now = new Date().getTime();
361
- while (!Timers.isEmpty()) {
362
- long k = Timers.firstKey();
363
- if (k > now)
364
- break;
365
-
366
- ArrayList<Long> callbacks = Timers.get(k);
367
- Timers.remove(k);
368
-
369
- // Fire all timers at this timestamp
370
- ListIterator<Long> iter = callbacks.listIterator(0);
371
- try {
372
- while (iter.hasNext()) {
373
- eventCallback (0, EM_TIMER_FIRED, null, iter.next().longValue());
374
- }
375
- } catch (UndeclaredThrowableException e) {
376
- e.printStackTrace();
377
- }
378
- }
379
- }
380
-
381
- public long installOneshotTimer (int milliseconds) {
382
- long s = createBinding();
383
- long deadline = new Date().getTime() + milliseconds;
384
-
385
- if (Timers.containsKey(deadline)) {
386
- Timers.get(deadline).add(s);
387
- } else {
388
- ArrayList<Long> callbacks = new ArrayList<Long>();
389
- callbacks.add(s);
390
- Timers.put(deadline, callbacks);
391
- }
392
-
393
- return s;
394
- }
395
-
396
- public long startTcpServer (SocketAddress sa) throws EmReactorException {
397
- try {
398
- ServerSocketChannel server = ServerSocketChannel.open();
399
- server.configureBlocking(false);
400
- server.socket().bind (sa);
401
- long s = createBinding();
402
- Acceptors.put(s, server);
403
- server.register(mySelector, SelectionKey.OP_ACCEPT, s);
404
- return s;
405
- } catch (IOException e) {
406
- throw new EmReactorException ("unable to open socket acceptor: " + e.toString());
407
- }
408
- }
409
-
410
- public long startTcpServer (String address, int port) throws EmReactorException {
411
- return startTcpServer (new InetSocketAddress (address, port));
412
- }
413
-
414
- public void stopTcpServer (long signature) throws IOException {
415
- ServerSocketChannel server = Acceptors.remove(signature);
416
- if (server != null)
417
- server.close();
418
- else
419
- throw new RuntimeException ("failed to close unknown acceptor");
420
- }
421
-
422
- public long openUdpSocket (InetSocketAddress address) throws IOException {
423
- // TODO, don't throw an exception out of here.
424
- DatagramChannel dg = DatagramChannel.open();
425
- dg.configureBlocking(false);
426
- dg.socket().bind(address);
427
- long b = createBinding();
428
- EventableChannel ec = new EventableDatagramChannel (dg, b, mySelector);
429
- dg.register(mySelector, SelectionKey.OP_READ, ec);
430
- Connections.put(b, ec);
431
- return b;
432
- }
433
-
434
- public long openUdpSocket (String address, int port) throws IOException {
435
- return openUdpSocket (new InetSocketAddress (address, port));
436
- }
437
-
438
- public void sendData (long sig, ByteBuffer bb) throws IOException {
439
- EventableChannel ec = Connections.get(sig);
440
- if (ec == null) {
441
- return;
442
- }
443
- ec.scheduleOutboundData( bb );
444
- // HACK: In Ubuntu(java version 1.6.0_33), it is blocked by mSelector.select() in checkIO() and writeOutboundData() is not called.
445
- if (!ec.isWatchOnly()) {
446
- ec.writeOutboundData();
447
- }
448
- }
449
-
450
- public void sendData (long sig, byte[] data) throws IOException {
451
- sendData (sig, ByteBuffer.wrap(data));
452
- }
453
-
454
- public void setCommInactivityTimeout (long sig, long mills) {
455
- Connections.get(sig).setCommInactivityTimeout (mills);
456
- }
457
-
458
- public void sendDatagram (long sig, byte[] data, int length, String recipAddress, int recipPort) {
459
- sendDatagram (sig, ByteBuffer.wrap(data), recipAddress, recipPort);
460
- }
461
-
462
- public void sendDatagram (long sig, ByteBuffer bb, String recipAddress, int recipPort) {
463
- (Connections.get(sig)).scheduleOutboundDatagram( bb, recipAddress, recipPort);
464
- }
465
-
466
- public long connectTcpServer (String address, int port) {
467
- return connectTcpServer(null, 0, address, port);
468
- }
469
-
470
- public long connectTcpServer (String bindAddr, int bindPort, String address, int port) {
471
- long b = createBinding();
472
-
473
- try {
474
- SocketChannel sc = SocketChannel.open();
475
- sc.configureBlocking(false);
476
- if (bindAddr != null)
477
- sc.socket().bind(new InetSocketAddress (bindAddr, bindPort));
478
-
479
- EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
480
-
481
- if (sc.connect (new InetSocketAddress (address, port))) {
482
- // Connection returned immediately. Can happen with localhost connections.
483
- // WARNING, this code is untested due to lack of available test conditions.
484
- // Ought to be be able to come here from a localhost connection, but that
485
- // doesn't happen on Linux. (Maybe on FreeBSD?)
486
- // The reason for not handling this until we can test it is that we
487
- // really need to return from this function WITHOUT triggering any EM events.
488
- // That's because until the user code has seen the signature we generated here,
489
- // it won't be able to properly dispatch them. The C++ EM deals with this
490
- // by setting pending mode as a flag in ALL eventable descriptors and making
491
- // the descriptor select for writable. Then, it can send UNBOUND and
492
- // CONNECTION_COMPLETED on the next pass through the loop, because writable will
493
- // fire.
494
- throw new RuntimeException ("immediate-connect unimplemented");
495
- }
496
- else {
497
- ec.setConnectPending();
498
- Connections.put (b, ec);
499
- NewConnections.add (b);
500
- }
501
- } catch (IOException e) {
502
- // Can theoretically come here if a connect failure can be determined immediately.
503
- // I don't know how to make that happen for testing purposes.
504
- throw new RuntimeException ("immediate-connect unimplemented: " + e.toString());
505
- }
506
- return b;
507
- }
508
-
509
- public void closeConnection (long sig, boolean afterWriting) {
510
- EventableChannel ec = Connections.get(sig);
511
- if (ec != null)
512
- if (ec.scheduleClose (afterWriting))
513
- UnboundConnections.add (sig);
514
- }
515
-
516
- long createBinding() {
517
- return ++BindingIndex;
518
- }
519
-
520
- public void signalLoopbreak() {
521
- loopBreaker.set(true);
522
- if (mySelector != null)
523
- mySelector.wakeup();
524
- }
525
-
526
- public void startTls (long sig) throws NoSuchAlgorithmException, KeyManagementException {
527
- Connections.get(sig).startTls();
528
- }
529
-
530
- public void setTimerQuantum (int mills) {
531
- if (mills < 5 || mills > 2500)
532
- throw new RuntimeException ("attempt to set invalid timer-quantum value: "+mills);
533
- timerQuantum = mills;
534
- }
535
-
536
- public Object[] getPeerName (long sig) {
537
- return Connections.get(sig).getPeerName();
538
- }
539
-
540
- public Object[] getSockName (long sig) {
541
- return Connections.get(sig).getSockName();
542
- }
543
-
544
- public long attachChannel (SocketChannel sc, boolean watch_mode) {
545
- long b = createBinding();
546
-
547
- EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
548
-
549
- ec.setAttached();
550
- if (watch_mode)
551
- ec.setWatchOnly();
552
-
553
- Connections.put (b, ec);
554
- NewConnections.add (b);
555
-
556
- return b;
557
- }
558
-
559
- public SocketChannel detachChannel (long sig) {
560
- EventableSocketChannel ec = (EventableSocketChannel) Connections.get (sig);
561
- if (ec != null) {
562
- UnboundConnections.add (sig);
563
- return ec.getChannel();
564
- } else {
565
- return null;
566
- }
567
- }
568
-
569
- public void setNotifyReadable (long sig, boolean mode) {
570
- ((EventableSocketChannel) Connections.get(sig)).setNotifyReadable(mode);
571
- }
572
-
573
- public void setNotifyWritable (long sig, boolean mode) {
574
- ((EventableSocketChannel) Connections.get(sig)).setNotifyWritable(mode);
575
- }
576
-
577
- public boolean isNotifyReadable (long sig) {
578
- return Connections.get(sig).isNotifyReadable();
579
- }
580
-
581
- public boolean isNotifyWritable (long sig) {
582
- return Connections.get(sig).isNotifyWritable();
583
- }
584
-
585
- public int getConnectionCount() {
586
- return Connections.size() + Acceptors.size();
587
- }
41
+ public final int EM_TIMER_FIRED = 100;
42
+ public final int EM_CONNECTION_READ = 101;
43
+ public final int EM_CONNECTION_UNBOUND = 102;
44
+ public final int EM_CONNECTION_ACCEPTED = 103;
45
+ public final int EM_CONNECTION_COMPLETED = 104;
46
+ public final int EM_LOOPBREAK_SIGNAL = 105;
47
+ public final int EM_CONNECTION_NOTIFY_READABLE = 106;
48
+ public final int EM_CONNECTION_NOTIFY_WRITABLE = 107;
49
+ public final int EM_SSL_HANDSHAKE_COMPLETED = 108;
50
+ public final int EM_SSL_VERIFY = 109;
51
+ public final int EM_PROXY_TARGET_UNBOUND = 110;
52
+ public final int EM_PROXY_COMPLETED = 111;
53
+
54
+ private Selector mySelector;
55
+ private TreeMap<Long, ArrayList<Long>> Timers;
56
+ private HashMap<Long, EventableChannel> Connections;
57
+ private HashMap<Long, ServerSocketChannel> Acceptors;
58
+ private ArrayList<Long> NewConnections;
59
+ private ArrayList<Long> UnboundConnections;
60
+ private ArrayList<EventableSocketChannel> DetachedConnections;
61
+
62
+ private boolean bRunReactor;
63
+ private long BindingIndex;
64
+ private AtomicBoolean loopBreaker;
65
+ private ByteBuffer myReadBuffer;
66
+ private int timerQuantum;
67
+
68
+ public EmReactor() {
69
+ Timers = new TreeMap<Long, ArrayList<Long>>();
70
+ Connections = new HashMap<Long, EventableChannel>();
71
+ Acceptors = new HashMap<Long, ServerSocketChannel>();
72
+ NewConnections = new ArrayList<Long>();
73
+ UnboundConnections = new ArrayList<Long>();
74
+ DetachedConnections = new ArrayList<EventableSocketChannel>();
75
+
76
+ BindingIndex = 0;
77
+ loopBreaker = new AtomicBoolean();
78
+ loopBreaker.set(false);
79
+ myReadBuffer = ByteBuffer.allocate(32*1024); // don't use a direct buffer. Ruby doesn't seem to like them.
80
+ timerQuantum = 98;
81
+ }
82
+
83
+ /**
84
+ * This is a no-op stub, intended to be overridden in user code.
85
+ */
86
+ public void eventCallback (long sig, int eventType, ByteBuffer data, long data2) {
87
+ System.out.println ("Default callback: "+sig+" "+eventType+" "+data+" "+data2);
88
+ }
89
+ public void eventCallback (long sig, int eventType, ByteBuffer data) {
90
+ eventCallback (sig, eventType, data, 0);
91
+ }
92
+
93
+
94
+ public void run() {
95
+ try {
96
+ mySelector = Selector.open();
97
+ bRunReactor = true;
98
+ } catch (IOException e) {
99
+ throw new RuntimeException ("Could not open selector", e);
100
+ }
101
+
102
+ while (bRunReactor) {
103
+ runLoopbreaks();
104
+ if (!bRunReactor) break;
105
+
106
+ runTimers();
107
+ if (!bRunReactor) break;
108
+
109
+ removeUnboundConnections();
110
+ checkIO();
111
+ addNewConnections();
112
+ processIO();
113
+ }
114
+
115
+ close();
116
+ }
117
+
118
+ void addNewConnections() {
119
+ ListIterator<EventableSocketChannel> iter = DetachedConnections.listIterator(0);
120
+ while (iter.hasNext()) {
121
+ EventableSocketChannel ec = iter.next();
122
+ ec.cleanup();
123
+ }
124
+ DetachedConnections.clear();
125
+
126
+ ListIterator<Long> iter2 = NewConnections.listIterator(0);
127
+ while (iter2.hasNext()) {
128
+ long b = iter2.next();
129
+
130
+ EventableChannel ec = Connections.get(b);
131
+ if (ec != null) {
132
+ try {
133
+ ec.register();
134
+ } catch (ClosedChannelException e) {
135
+ UnboundConnections.add (ec.getBinding());
136
+ }
137
+ }
138
+ }
139
+ NewConnections.clear();
140
+ }
141
+
142
+ void removeUnboundConnections() {
143
+ ListIterator<Long> iter = UnboundConnections.listIterator(0);
144
+ while (iter.hasNext()) {
145
+ long b = iter.next();
146
+
147
+ EventableChannel ec = Connections.remove(b);
148
+ if (ec != null) {
149
+ eventCallback (b, EM_CONNECTION_UNBOUND, null);
150
+ ec.close();
151
+
152
+ EventableSocketChannel sc = (EventableSocketChannel) ec;
153
+ if (sc != null && sc.isAttached())
154
+ DetachedConnections.add (sc);
155
+ }
156
+ }
157
+ UnboundConnections.clear();
158
+ }
159
+
160
+ void checkIO() {
161
+ long timeout;
162
+
163
+ if (NewConnections.size() > 0) {
164
+ timeout = -1;
165
+ } else if (!Timers.isEmpty()) {
166
+ long now = new Date().getTime();
167
+ long k = Timers.firstKey();
168
+ long diff = k-now;
169
+
170
+ if (diff <= 0)
171
+ timeout = -1; // don't wait, just poll once
172
+ else
173
+ timeout = diff;
174
+ } else {
175
+ timeout = 0; // wait indefinitely
176
+ }
177
+
178
+ try {
179
+ if (timeout == -1)
180
+ mySelector.selectNow();
181
+ else
182
+ mySelector.select(timeout);
183
+ } catch (IOException e) {
184
+ e.printStackTrace();
185
+ }
186
+ }
187
+
188
+ void processIO() {
189
+ Iterator<SelectionKey> it = mySelector.selectedKeys().iterator();
190
+ while (it.hasNext()) {
191
+ SelectionKey k = it.next();
192
+ it.remove();
193
+
194
+ if (k.isConnectable())
195
+ isConnectable(k);
196
+
197
+ else if (k.isAcceptable())
198
+ isAcceptable(k);
199
+
200
+ else {
201
+ if (k.isWritable())
202
+ isWritable(k);
203
+
204
+ if (k.isReadable())
205
+ isReadable(k);
206
+ }
207
+ }
208
+ }
209
+
210
+ void isAcceptable (SelectionKey k) {
211
+ ServerSocketChannel ss = (ServerSocketChannel) k.channel();
212
+ SocketChannel sn;
213
+ long b;
214
+
215
+ for (int n = 0; n < 10; n++) {
216
+ try {
217
+ sn = ss.accept();
218
+ if (sn == null)
219
+ break;
220
+ } catch (IOException e) {
221
+ e.printStackTrace();
222
+ k.cancel();
223
+
224
+ ServerSocketChannel server = Acceptors.remove(k.attachment());
225
+ if (server != null)
226
+ try{ server.close(); } catch (IOException ex) {};
227
+ break;
228
+ }
229
+
230
+ try {
231
+ sn.configureBlocking(false);
232
+ } catch (IOException e) {
233
+ e.printStackTrace();
234
+ continue;
235
+ }
236
+
237
+ b = createBinding();
238
+ EventableSocketChannel ec = new EventableSocketChannel (sn, b, mySelector);
239
+ Connections.put (b, ec);
240
+ NewConnections.add (b);
241
+
242
+ eventCallback (((Long)k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b);
243
+ }
244
+ }
245
+
246
+ void isReadable (SelectionKey k) {
247
+ EventableChannel ec = (EventableChannel) k.attachment();
248
+ long b = ec.getBinding();
249
+
250
+ if (ec.isWatchOnly()) {
251
+ if (ec.isNotifyReadable())
252
+ eventCallback (b, EM_CONNECTION_NOTIFY_READABLE, null);
253
+ } else {
254
+ myReadBuffer.clear();
255
+
256
+ try {
257
+ ec.readInboundData (myReadBuffer);
258
+ myReadBuffer.flip();
259
+ if (myReadBuffer.limit() > 0)
260
+ eventCallback (b, EM_CONNECTION_READ, myReadBuffer);
261
+ } catch (IOException e) {
262
+ UnboundConnections.add (b);
263
+ }
264
+ }
265
+ }
266
+
267
+ void isWritable (SelectionKey k) {
268
+ EventableChannel ec = (EventableChannel) k.attachment();
269
+ long b = ec.getBinding();
270
+
271
+ if (ec.isWatchOnly()) {
272
+ if (ec.isNotifyWritable())
273
+ eventCallback (b, EM_CONNECTION_NOTIFY_WRITABLE, null);
274
+ }
275
+ else {
276
+ try {
277
+ if (!ec.writeOutboundData())
278
+ UnboundConnections.add (b);
279
+ } catch (IOException e) {
280
+ UnboundConnections.add (b);
281
+ }
282
+ }
283
+ }
284
+
285
+ void isConnectable (SelectionKey k) {
286
+ EventableSocketChannel ec = (EventableSocketChannel) k.attachment();
287
+ long b = ec.getBinding();
288
+
289
+ try {
290
+ if (ec.finishConnecting())
291
+ eventCallback (b, EM_CONNECTION_COMPLETED, null);
292
+ else
293
+ UnboundConnections.add (b);
294
+ } catch (IOException e) {
295
+ UnboundConnections.add (b);
296
+ }
297
+ }
298
+
299
+ void close() {
300
+ try {
301
+ if (mySelector != null)
302
+ mySelector.close();
303
+ } catch (IOException e) {}
304
+ mySelector = null;
305
+
306
+ // run down open connections and sockets.
307
+ Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
308
+ while (i.hasNext()) {
309
+ try {
310
+ i.next().close();
311
+ } catch (IOException e) {}
312
+ }
313
+
314
+ // 29Sep09: We create an ArrayList of the existing connections, then iterate over
315
+ // that to call unbind on them. This is because an unbind can trigger a reconnect,
316
+ // which will add to the Connections HashMap, causing a ConcurrentModificationException.
317
+ // XXX: The correct behavior here would be to latch the various reactor methods to return
318
+ // immediately if the reactor is shutting down.
319
+ ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
320
+ Iterator<EventableChannel> i2 = Connections.values().iterator();
321
+ while (i2.hasNext()) {
322
+ EventableChannel ec = i2.next();
323
+ if (ec != null) {
324
+ conns.add (ec);
325
+ }
326
+ }
327
+ Connections.clear();
328
+
329
+ ListIterator<EventableChannel> i3 = conns.listIterator(0);
330
+ while (i3.hasNext()) {
331
+ EventableChannel ec = i3.next();
332
+ eventCallback (ec.getBinding(), EM_CONNECTION_UNBOUND, null);
333
+ ec.close();
334
+
335
+ EventableSocketChannel sc = (EventableSocketChannel) ec;
336
+ if (sc != null && sc.isAttached())
337
+ DetachedConnections.add (sc);
338
+ }
339
+
340
+ ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
341
+ while (i4.hasNext()) {
342
+ EventableSocketChannel ec = i4.next();
343
+ ec.cleanup();
344
+ }
345
+ DetachedConnections.clear();
346
+ }
347
+
348
+ void runLoopbreaks() {
349
+ if (loopBreaker.getAndSet(false)) {
350
+ eventCallback (0, EM_LOOPBREAK_SIGNAL, null);
351
+ }
352
+ }
353
+
354
+ public void stop() {
355
+ bRunReactor = false;
356
+ signalLoopbreak();
357
+ }
358
+
359
+ void runTimers() {
360
+ long now = new Date().getTime();
361
+ while (!Timers.isEmpty()) {
362
+ long k = Timers.firstKey();
363
+ if (k > now)
364
+ break;
365
+
366
+ ArrayList<Long> callbacks = Timers.get(k);
367
+ Timers.remove(k);
368
+
369
+ // Fire all timers at this timestamp
370
+ ListIterator<Long> iter = callbacks.listIterator(0);
371
+ try {
372
+ while (iter.hasNext()) {
373
+ eventCallback (0, EM_TIMER_FIRED, null, iter.next().longValue());
374
+ }
375
+ } catch (UndeclaredThrowableException e) {
376
+ e.printStackTrace();
377
+ }
378
+ }
379
+ }
380
+
381
+ public long installOneshotTimer (int milliseconds) {
382
+ long s = createBinding();
383
+ long deadline = new Date().getTime() + milliseconds;
384
+
385
+ if (Timers.containsKey(deadline)) {
386
+ Timers.get(deadline).add(s);
387
+ } else {
388
+ ArrayList<Long> callbacks = new ArrayList<Long>();
389
+ callbacks.add(s);
390
+ Timers.put(deadline, callbacks);
391
+ }
392
+
393
+ return s;
394
+ }
395
+
396
+ public long startTcpServer (SocketAddress sa) throws EmReactorException {
397
+ try {
398
+ ServerSocketChannel server = ServerSocketChannel.open();
399
+ server.configureBlocking(false);
400
+ server.socket().bind (sa);
401
+ long s = createBinding();
402
+ Acceptors.put(s, server);
403
+ server.register(mySelector, SelectionKey.OP_ACCEPT, s);
404
+ return s;
405
+ } catch (IOException e) {
406
+ throw new EmReactorException ("unable to open socket acceptor: " + e.toString());
407
+ }
408
+ }
409
+
410
+ public long startTcpServer (String address, int port) throws EmReactorException {
411
+ return startTcpServer (new InetSocketAddress (address, port));
412
+ }
413
+
414
+ public void stopTcpServer (long signature) throws IOException {
415
+ ServerSocketChannel server = Acceptors.remove(signature);
416
+ if (server != null)
417
+ server.close();
418
+ else
419
+ throw new RuntimeException ("failed to close unknown acceptor");
420
+ }
421
+
422
+ public long openUdpSocket (InetSocketAddress address) throws IOException {
423
+ // TODO, don't throw an exception out of here.
424
+ DatagramChannel dg = DatagramChannel.open();
425
+ dg.configureBlocking(false);
426
+ dg.socket().bind(address);
427
+ long b = createBinding();
428
+ EventableChannel ec = new EventableDatagramChannel (dg, b, mySelector);
429
+ dg.register(mySelector, SelectionKey.OP_READ, ec);
430
+ Connections.put(b, ec);
431
+ return b;
432
+ }
433
+
434
+ public long openUdpSocket (String address, int port) throws IOException {
435
+ return openUdpSocket (new InetSocketAddress (address, port));
436
+ }
437
+
438
+ public void sendData (long sig, ByteBuffer bb) throws IOException {
439
+ EventableChannel ec = Connections.get(sig);
440
+ if (ec == null) {
441
+ return;
442
+ }
443
+ ec.scheduleOutboundData( bb );
444
+ // HACK: In Ubuntu(java version 1.6.0_33), it is blocked by mSelector.select() in checkIO() and writeOutboundData() is not called.
445
+ if (!ec.isWatchOnly()) {
446
+ ec.writeOutboundData();
447
+ }
448
+ }
449
+
450
+ public void sendData (long sig, byte[] data) throws IOException {
451
+ sendData (sig, ByteBuffer.wrap(data));
452
+ }
453
+
454
+ public void setCommInactivityTimeout (long sig, long mills) {
455
+ Connections.get(sig).setCommInactivityTimeout (mills);
456
+ }
457
+
458
+ public void sendDatagram (long sig, byte[] data, int length, String recipAddress, int recipPort) {
459
+ sendDatagram (sig, ByteBuffer.wrap(data), recipAddress, recipPort);
460
+ }
461
+
462
+ public void sendDatagram (long sig, ByteBuffer bb, String recipAddress, int recipPort) {
463
+ (Connections.get(sig)).scheduleOutboundDatagram( bb, recipAddress, recipPort);
464
+ }
465
+
466
+ public long connectTcpServer (String address, int port) {
467
+ return connectTcpServer(null, 0, address, port);
468
+ }
469
+
470
+ public long connectTcpServer (String bindAddr, int bindPort, String address, int port) {
471
+ long b = createBinding();
472
+
473
+ try {
474
+ SocketChannel sc = SocketChannel.open();
475
+ sc.configureBlocking(false);
476
+ if (bindAddr != null)
477
+ sc.socket().bind(new InetSocketAddress (bindAddr, bindPort));
478
+
479
+ EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
480
+
481
+ if (sc.connect (new InetSocketAddress (address, port))) {
482
+ // Connection returned immediately. Can happen with localhost connections.
483
+ // WARNING, this code is untested due to lack of available test conditions.
484
+ // Ought to be be able to come here from a localhost connection, but that
485
+ // doesn't happen on Linux. (Maybe on FreeBSD?)
486
+ // The reason for not handling this until we can test it is that we
487
+ // really need to return from this function WITHOUT triggering any EM events.
488
+ // That's because until the user code has seen the signature we generated here,
489
+ // it won't be able to properly dispatch them. The C++ EM deals with this
490
+ // by setting pending mode as a flag in ALL eventable descriptors and making
491
+ // the descriptor select for writable. Then, it can send UNBOUND and
492
+ // CONNECTION_COMPLETED on the next pass through the loop, because writable will
493
+ // fire.
494
+ throw new RuntimeException ("immediate-connect unimplemented");
495
+ }
496
+ else {
497
+ ec.setConnectPending();
498
+ Connections.put (b, ec);
499
+ NewConnections.add (b);
500
+ }
501
+ } catch (IOException e) {
502
+ // Can theoretically come here if a connect failure can be determined immediately.
503
+ // I don't know how to make that happen for testing purposes.
504
+ throw new RuntimeException ("immediate-connect unimplemented: " + e.toString());
505
+ }
506
+ return b;
507
+ }
508
+
509
+ public void closeConnection (long sig, boolean afterWriting) {
510
+ EventableChannel ec = Connections.get(sig);
511
+ if (ec != null)
512
+ if (ec.scheduleClose (afterWriting))
513
+ UnboundConnections.add (sig);
514
+ }
515
+
516
+ long createBinding() {
517
+ return ++BindingIndex;
518
+ }
519
+
520
+ public void signalLoopbreak() {
521
+ loopBreaker.set(true);
522
+ if (mySelector != null)
523
+ mySelector.wakeup();
524
+ }
525
+
526
+ public void startTls (long sig) throws NoSuchAlgorithmException, KeyManagementException {
527
+ Connections.get(sig).startTls();
528
+ }
529
+
530
+ public void setTimerQuantum (int mills) {
531
+ if (mills < 5 || mills > 2500)
532
+ throw new RuntimeException ("attempt to set invalid timer-quantum value: "+mills);
533
+ timerQuantum = mills;
534
+ }
535
+
536
+ public Object[] getPeerName (long sig) {
537
+ return Connections.get(sig).getPeerName();
538
+ }
539
+
540
+ public Object[] getSockName (long sig) {
541
+ return Connections.get(sig).getSockName();
542
+ }
543
+
544
+ public long attachChannel (SocketChannel sc, boolean watch_mode) {
545
+ long b = createBinding();
546
+
547
+ EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
548
+
549
+ ec.setAttached();
550
+ if (watch_mode)
551
+ ec.setWatchOnly();
552
+
553
+ Connections.put (b, ec);
554
+ NewConnections.add (b);
555
+
556
+ return b;
557
+ }
558
+
559
+ public SocketChannel detachChannel (long sig) {
560
+ EventableSocketChannel ec = (EventableSocketChannel) Connections.get (sig);
561
+ if (ec != null) {
562
+ UnboundConnections.add (sig);
563
+ return ec.getChannel();
564
+ } else {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ public void setNotifyReadable (long sig, boolean mode) {
570
+ ((EventableSocketChannel) Connections.get(sig)).setNotifyReadable(mode);
571
+ }
572
+
573
+ public void setNotifyWritable (long sig, boolean mode) {
574
+ ((EventableSocketChannel) Connections.get(sig)).setNotifyWritable(mode);
575
+ }
576
+
577
+ public boolean isNotifyReadable (long sig) {
578
+ return Connections.get(sig).isNotifyReadable();
579
+ }
580
+
581
+ public boolean isNotifyWritable (long sig) {
582
+ return Connections.get(sig).isNotifyWritable();
583
+ }
584
+
585
+ public int getConnectionCount() {
586
+ return Connections.size() + Acceptors.size();
587
+ }
588
588
  }