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));
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 }
257 }
258 }
259
260 private void processSessions(Set<SelectionKey> keys) {
261 for (SelectionKey key : keys) {
262 if (!key.isConnectable())
263 continue;
264
265 SocketChannel ch = (SocketChannel) key.channel();
266 ConnectionRequest entry = (ConnectionRequest) key.attachment();
267
268 boolean success = false;
269 try {
270 ch.finishConnect();
271 newSession(ch, entry.handler, entry.config, entry);
272 success = true;
273 } catch (Throwable e) {
274 entry.setException(e);
275 } finally {
276 key.cancel();
277 if (!success) {
278 try {
279 ch.close();
280 } catch (IOException e) {
281 ExceptionMonitor.getInstance().exceptionCaught(e);
282 }
283 }
284 }
285 }
286
287 keys.clear();
288 }
289
290 private void processTimedOutSessions(Set<SelectionKey> keys) {
291 long currentTime = System.currentTimeMillis();
292
293 for (SelectionKey key : keys) {
294 if (!key.isValid())
295 continue;
296
297 ConnectionRequest entry = (ConnectionRequest) key.attachment();
298
299 if (currentTime >= entry.deadline) {
300 entry.setException(new ConnectException());
301 try {
302 key.channel().close();
303 } catch (IOException e) {
304 ExceptionMonitor.getInstance().exceptionCaught(e);
305 } finally {
306 key.cancel();
307 }
308 }
309 }
310 }
311
312 private void newSession(SocketChannel ch, IoHandler handler,
313 IoServiceConfig config, ConnectFuture connectFuture)
314 throws IOException {
315 SocketSessionImpl session = new SocketSessionImpl(this,
316 nextProcessor(), getListeners(), config, ch, handler, ch
317 .socket().getRemoteSocketAddress());
318 try {
319 getFilterChainBuilder().buildFilterChain(session.getFilterChain());
320 config.getFilterChainBuilder().buildFilterChain(
321 session.getFilterChain());
322 config.getThreadModel().buildFilterChain(session.getFilterChain());
323 } catch (Throwable e) {
324 throw (IOException) new IOException("Failed to create a session.")
325 .initCause(e);
326 }
327
328
329
330 session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE,
331 connectFuture);
332
333
334 session.getIoProcessor().addNew(session);
335 }
336
337 private SocketIoProcessor nextProcessor() {
338 if (this.processorDistributor == Integer.MAX_VALUE) {
339 this.processorDistributor = Integer.MAX_VALUE % this.processorCount;
340 }
341
342 return ioProcessors[processorDistributor++ % processorCount];
343 }
344
345 private class Worker implements Runnable {
346 private long lastActive = System.currentTimeMillis();
347
348 public void run() {
349 Thread.currentThread().setName(SocketConnector.this.threadName);
350
351 Selector selector = SocketConnector.this.selector;
352 for (;;) {
353 try {
354 int nKeys = selector.select(1000);
355
356 registerNew();
357
358 if (nKeys > 0) {
359 processSessions(selector.selectedKeys());
360 }
361
362 processTimedOutSessions(selector.keys());
363
364 if (selector.keys().isEmpty()) {
365 if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L) {
366 synchronized (lock) {
367 if (selector.keys().isEmpty()
368 && connectQueue.isEmpty()) {
369 worker = null;
370 try {
371 selector.close();
372 } catch (IOException e) {
373 ExceptionMonitor.getInstance()
374 .exceptionCaught(e);
375 } finally {
376 SocketConnector.this.selector = null;
377 }
378 break;
379 }
380 }
381 }
382 } else {
383 lastActive = System.currentTimeMillis();
384 }
385 } catch (IOException e) {
386 ExceptionMonitor.getInstance().exceptionCaught(e);
387
388 try {
389 Thread.sleep(1000);
390 } catch (InterruptedException e1) {
391 ExceptionMonitor.getInstance().exceptionCaught(e1);
392 }
393 }
394 }
395 }
396 }
397
398 private class ConnectionRequest extends DefaultConnectFuture {
399 private final SocketChannel channel;
400
401 private final long deadline;
402
403 private final IoHandler handler;
404
405 private final IoServiceConfig config;
406
407 private ConnectionRequest(SocketChannel channel, IoHandler handler,
408 IoServiceConfig config) {
409 this.channel = channel;
410 long timeout;
411 if (config instanceof IoConnectorConfig) {
412 timeout = ((IoConnectorConfig) config)
413 .getConnectTimeoutMillis();
414 } else {
415 timeout = ((IoConnectorConfig) getDefaultConfig())
416 .getConnectTimeoutMillis();
417 }
418 this.deadline = System.currentTimeMillis() + timeout;
419 this.handler = handler;
420 this.config = config;
421 }
422 }
423 }