?? reactor.java
字號:
package net;
import java.nio.channels.*;
import java.nio.channels.ServerSocketChannel;
import java.net.*;
import java.util.*;
import java.io.*;
/**
* 反應器<br>
* 通過構造方法產生一個反應器(選擇器),構造Unix系統常用的網絡通信select架構<br>
* 通過KVM內部的select結構,對網絡事件做出反應,比如連接,讀,寫等。
*
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class Reactor
implements Runnable {
private final Selector selector;
private final ServerSocketChannel serverSocketChannel;
private final NetListener processor;
private boolean shutdown = false;
/**
* 構造方法
*
* @param port int
* @param processor AcceptionListener
* @throws IOException
*/
public Reactor(int port, NetListener processor) throws IOException {
this.processor = processor;
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress(port);
serverSocketChannel.socket().bind(isa); //綁定
serverSocketChannel.configureBlocking(false); //非阻塞
SelectionKey sk = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); //注冊監聽選擇器
sk.attach(new Acceptor());
}
public void shutdown() {
shutdown = true;
}
/**
* 選擇器線程,此線程會對所有連接的讀寫進行響應,通過回調Handle和Acceptor的run()方法實現。
*/
public void run() {
try {
while (!shutdown) {
int num = selector.select();
//select方法可能返回為0
//所以加上此判斷
if (num > 0) {
Set selected = selector.selectedKeys();
Iterator it = selected.iterator();
while (it.hasNext()) {
dispatch( (SelectionKey) it.next());
}
selected.clear();
}
synchronized (this) {
try {
wait(100);
}
catch (InterruptedException ex) {
}
}
} //end while
}
catch (IOException e) {
}
}
/**
* 任務分發
* @param k SelectionKey
*/
private void dispatch(SelectionKey k) {
Runnable r = (Runnable) k.attachment();
if (r != null) {
r.run();
}
}
/**
* 接收者,當監聽到一個連接請求時,產生一個接收者
*
* 這個任務產生一個Handle,Handle實際上是一個連接的管理器,負責對一個客戶的所有通信進行管理
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
class Acceptor
implements Runnable {
/**
* 反應器回調接口
*/
public void run() {
try {
System.out.println("Acceptor:" + this);
SocketChannel sc = serverSocketChannel.accept();
sc.configureBlocking(false);
if (sc != null) {
//accpet后將key的attach轉到handle上面
Handler h = new Handler(selector, sc);
//如果網絡監聽器不為空,則執行定制操作
if (processor != null) {
processor.onAccept(h);
}
}
}
catch (IOException e) {
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -