-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAcceptor.java
More file actions
81 lines (71 loc) · 2.93 KB
/
Acceptor.java
File metadata and controls
81 lines (71 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.janekey.httpserver.net;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* User: janekey
* Date: 14-11-14
* Time: 下午5:21
*/
public class Acceptor implements Runnable {
protected static final int DEFAULT_IO_TIMEOUT_MILLIS = 30000;//原30秒
protected Processor[] processors;
protected Selector selector;
private Filter filter; //过滤器
protected Handler handler; //处理器
protected String name; //名称
public Acceptor(String name, Filter filter, Handler handler, InetSocketAddress bindAddress) {
try {
selector = Selector.open();
this.name = name;
this.filter = filter;
this.handler = handler;
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(bindAddress);
SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
key.attach(DEFAULT_IO_TIMEOUT_MILLIS);
} catch (Throwable th) {
Logger.log(th, "Acceptor Constructor Error");
throw new RuntimeException(th);
}
}
@Override
public void run() {
try {
int sessionId = 0;
while (true) {
int n = selector.select();
if (n > 0) {
Iterator<SelectionKey> readyKeys = selector.selectedKeys().iterator();
while (readyKeys.hasNext()) {
SelectionKey key = readyKeys.next();
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
int processorNum = Math.abs(sessionId) % processors.length;
int ioTimeoutMillis = (Integer) key.attachment();
processors[processorNum].scheduleRegister(socketChannel, sessionId, ioTimeoutMillis);
sessionId++;
readyKeys.remove();
}
}
}
} catch (Throwable th) {
Logger.log(th, "Acceptor run error");
}
}
public synchronized void listen() {
try {
int processorCount = Runtime.getRuntime().availableProcessors() + 1;
processors = new Processor[processorCount];
for (int i = 0; i < processorCount; i++) processors[i] = new Processor(name, filter, handler, i);
new Thread(this, name + "-Acceptor").start();
} catch (Throwable th) {
Logger.log(th, "Acceptor listen error");
throw new RuntimeException(th);
}
}
}