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;
21
22 import java.io.IOException;
23 import java.net.ConnectException;
24 import java.net.InetSocketAddress;
25 import java.net.SocketAddress;
26 import java.nio.channels.SelectionKey;
27 import java.nio.channels.Selector;
28 import java.nio.channels.SocketChannel;
29 import java.util.Queue;
30 import java.util.Set;
31 import java.util.concurrent.ConcurrentLinkedQueue;
32 import java.util.concurrent.Executor;
33 import java.util.concurrent.atomic.AtomicInteger;
34
35 import org.apache.mina.common.ConnectFuture;
36 import org.apache.mina.common.ExceptionMonitor;
37 import org.apache.mina.common.IoConnector;
38 import org.apache.mina.common.IoConnectorConfig;
39 import org.apache.mina.common.IoHandler;
40 import org.apache.mina.common.IoServiceConfig;
41 import org.apache.mina.common.support.AbstractIoFilterChain;
42 import org.apache.mina.common.support.BaseIoConnector;
43 import org.apache.mina.common.support.DefaultConnectFuture;
44 import org.apache.mina.util.NamePreservingRunnable;
45 import org.apache.mina.util.NewThreadExecutor;
46
47
48
49
50
51
52
53 public class SocketConnector extends BaseIoConnector {
54 private static final AtomicInteger nextId = new AtomicInteger();
55
56 private final Object lock = new Object();
57
58 private final int id = nextId.getAndIncrement();
59
60 private final String threadName = "SocketConnector-" + id;
61
62 private SocketConnectorConfig defaultConfig = new SocketConnectorConfig();
63
64 private final Queue<ConnectionRequest> connectQueue = new ConcurrentLinkedQueue<ConnectionRequest>();
65
66 private final SocketIoProcessor[] ioProcessors;
67
68 private final int processorCount;
69
70 private final Executor executor;
71
72 private volatile Selector selector;
73
74 private Worker worker;
75
76 private int processorDistributor = 0;
77
78 private int workerTimeout = 60;
79
80
81
82
83 public SocketConnector() {
84 this(1, new NewThreadExecutor());
85 }
86
87
88
89
90
91
92
93 public SocketConnector(int processorCount, Executor executor) {
94 if (processorCount < 1) {
95 throw new IllegalArgumentException(
96 "Must have at least one processor");
97 }
98
99 this.executor = executor;
100 this.processorCount = processorCount;
101 ioProcessors = new SocketIoProcessor[processorCount];
102
103 for (int i = 0; i < processorCount; i++) {
104 ioProcessors[i] = new SocketIoProcessor(
105 "SocketConnectorIoProcessor-" + id + "." + i, executor);
106 }
107 }
108
109
110
111
112
113
114
115
116 public int getWorkerTimeout() {
117 return workerTimeout;
118 }
119
120
121
122
123
124
125
126
127
128 public void setWorkerTimeout(int workerTimeout) {
129 if (workerTimeout < 0) {
130 throw new IllegalArgumentException("Must be >= 0");
131 }
132 this.workerTimeout = workerTimeout;
133 }
134
135 public ConnectFuture connect(SocketAddress address, IoHandler handler,
136 IoServiceConfig config) {
137 return connect(address, null, handler, config);
138 }
139
140 public ConnectFuture connect(SocketAddress address,
141 SocketAddress localAddress, IoHandler handler,
142 IoServiceConfig config) {
143 if (address == null)
144 throw new NullPointerException("address");
145 if (handler == null)
146 throw new NullPointerException("handler");
147
148 if (!(address instanceof InetSocketAddress))
149 throw new IllegalArgumentException("Unexpected address type: "
150 + address.getClass());
151
152 if (localAddress != null
153 && !(localAddress instanceof InetSocketAddress))
154 throw new IllegalArgumentException(
155 "Unexpected local address type: " + localAddress.getClass());
156
157 if (config == null) {
158 config = getDefaultConfig();
159 }
160
161 SocketChannel ch = null;
162 boolean success = false;
163 try {
164 ch = SocketChannel.open();
165 ch.socket().setReuseAddress(true);
166 if (localAddress != null) {
167 ch.socket().bind(localAddress);
168 }
169
170 ch.configureBlocking(false);
171
172 if (ch.connect(address)) {
173 DefaultConnectFuture future = new DefaultConnectFuture();
174 newSession(ch, handler, config, future);
175 success = true;
176 return future;
177 }
178
179 success = true;
180 } catch (IOException e) {
181 return DefaultConnectFuture.newFailedFuture(e);
182 } finally {
183 if (!success && ch != null) {
184 try {
185 ch.close();
186 } catch (IOException e) {
187 ExceptionMonitor.getInstance().exceptionCaught(e);
188 }
189 }
190 }
191
192 ConnectionRequest request = new ConnectionRequest(ch, handler, config);
193 synchronized (lock) {
194 try {
195 startupWorker();
196 } catch (IOException e) {
197 try {
198 ch.close();
199 } catch (IOException e2) {
200 ExceptionMonitor.getInstance().exceptionCaught(e2);
201 }
202
203 return DefaultConnectFuture.newFailedFuture(e);
204 }
205
206 connectQueue.add(request);
207 selector.wakeup();
208 }
209
210 return request;
211 }
212
213 public SocketConnectorConfig getDefaultConfig() {
214 return defaultConfig;
215 }
216
217
218
219
220
221
222
223 public void setDefaultConfig(SocketConnectorConfig defaultConfig) {
224 if (defaultConfig == null) {
225 throw new NullPointerException("defaultConfig");
226 }
227 this.defaultConfig = defaultConfig;
228 }
229
230 private void startupWorker() throws IOException {
231 synchronized (lock) {
232 if (worker == null) {
233 selector = Selector.open();
234 worker = new Worker();
235 executor.execute(new NamePreservingRunnable(worker, threadName));
236 }
237 }
238 }
239
240 private void registerNew() {
241 if (connectQueue.isEmpty())
242 return;
243
244 Selector selector = this.selector;
245 for (;;) {
246 ConnectionRequest req = connectQueue.poll();
247
248 if (req == null)
249 break;
250
251 SocketChannel ch = req.channel;
252 try {
253 ch.register(selector, SelectionKey.OP_CONNECT, req);
254 } catch (IOException e) {
255 req.setException(e);
256 try {
257 ch.close();
258 } catch (IOException e2) {
259 ExceptionMonitor.getInstance().exceptionCaught(e2);
260 }
261 }
262 }
263 }
264
265 private void processSessions(Set<SelectionKey> keys) {
266 for (SelectionKey key : keys) {
267 if (!key.isConnectable())
268 continue;
269
270 SocketChannel ch = (SocketChannel) key.channel();
271 ConnectionRequest entry = (ConnectionRequest) key.attachment();
272
273 boolean success = false;
274 try {
275 ch.finishConnect();
276 newSession(ch, entry.handler, entry.config, entry);
277 success = true;
278 } catch (Throwable e) {
279 entry.setException(e);
280 } finally {
281 key.cancel();
282 if (!success) {
283 try {
284 ch.close();
285 } catch (IOException e) {
286 ExceptionMonitor.getInstance().exceptionCaught(e);
287 }
288 }
289 }
290 }
291
292 keys.clear();
293 }
294
295 private void processTimedOutSessions(Set<SelectionKey> keys) {
296 long currentTime = System.currentTimeMillis();
297
298 for (SelectionKey key : keys) {
299 if (!key.isValid())
300 continue;
301
302 ConnectionRequest entry = (ConnectionRequest) key.attachment();
303
304 if (currentTime >= entry.deadline) {
305 entry.setException(new ConnectException());
306 try {
307 key.channel().close();
308 } catch (IOException e) {
309 ExceptionMonitor.getInstance().exceptionCaught(e);
310 } finally {
311 key.cancel();
312 }
313 }
314 }
315 }
316
317 private void newSession(SocketChannel ch, IoHandler handler,
318 IoServiceConfig config, ConnectFuture connectFuture)
319 throws IOException {
320 SocketSessionImpl session = new SocketSessionImpl(this,
321 nextProcessor(), getListeners(), config, ch, handler, ch
322 .socket().getRemoteSocketAddress());
323 try {
324 getFilterChainBuilder().buildFilterChain(session.getFilterChain());
325 config.getFilterChainBuilder().buildFilterChain(
326 session.getFilterChain());
327 config.getThreadModel().buildFilterChain(session.getFilterChain());
328 } catch (Throwable e) {
329 throw (IOException) new IOException("Failed to create a session.")
330 .initCause(e);
331 }
332
333
334
335 session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE,
336 connectFuture);
337
338
339 session.getIoProcessor().addNew(session);
340 }
341
342 private SocketIoProcessor nextProcessor() {
343 if (this.processorDistributor == Integer.MAX_VALUE) {
344 this.processorDistributor = Integer.MAX_VALUE % this.processorCount;
345 }
346
347 return ioProcessors[processorDistributor++ % processorCount];
348 }
349
350 private class Worker implements Runnable {
351 private long lastActive = System.currentTimeMillis();
352
353 public void run() {
354 Selector selector = SocketConnector.this.selector;
355 for (;;) {
356 try {
357 int nKeys = selector.select(1000);
358
359 registerNew();
360
361 if (nKeys > 0) {
362 processSessions(selector.selectedKeys());
363 }
364
365 processTimedOutSessions(selector.keys());
366
367 if (selector.keys().isEmpty()) {
368 if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L) {
369 synchronized (lock) {
370 if (selector.keys().isEmpty()
371 && connectQueue.isEmpty()) {
372 worker = null;
373 try {
374 selector.close();
375 } catch (IOException e) {
376 ExceptionMonitor.getInstance()
377 .exceptionCaught(e);
378 } finally {
379 SocketConnector.this.selector = null;
380 }
381 break;
382 }
383 }
384 }
385 } else {
386 lastActive = System.currentTimeMillis();
387 }
388 } catch (IOException e) {
389 ExceptionMonitor.getInstance().exceptionCaught(e);
390
391 try {
392 Thread.sleep(1000);
393 } catch (InterruptedException e1) {
394 ExceptionMonitor.getInstance().exceptionCaught(e1);
395 }
396 }
397 }
398 }
399 }
400
401 private class ConnectionRequest extends DefaultConnectFuture {
402 private final SocketChannel channel;
403
404 private final long deadline;
405
406 private final IoHandler handler;
407
408 private final IoServiceConfig config;
409
410 private ConnectionRequest(SocketChannel channel, IoHandler handler,
411 IoServiceConfig config) {
412 this.channel = channel;
413 long timeout;
414 if (config instanceof IoConnectorConfig) {
415 timeout = ((IoConnectorConfig) config)
416 .getConnectTimeoutMillis();
417 } else {
418 timeout = ((IoConnectorConfig) getDefaultConfig())
419 .getConnectTimeoutMillis();
420 }
421 this.deadline = System.currentTimeMillis() + timeout;
422 this.handler = handler;
423 this.config = config;
424 }
425 }
426 }