⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reactor.java

📁 短信发送
💻 JAVA
字号:
/**
 * Created at Nov 22, 2008
 */
package com.jdev.net.connector;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
import com.jdev.net.event.Notifier;
import com.jdev.util.Debug;



/**
 * <p>Title: Reactor</p>
 * <p>Description: </p>
 * @author Lawrence
 * @version 1.0
 */
public class Reactor implements Runnable {

	private final static String module = Reactor.class.getName();
	private final Selector selector;
	private final ServerSocketChannel ssc;
	protected Notifier notifier;
	private int port;
	
	/**
	 * 创建主控服务线程
	 * 
	 * @param port
	 *            服务端口
	 * @throws java.lang.Exception
	 */
	public Reactor(int port) throws IOException {
		this.port = port;

		// 获取事件触发器
		notifier = Notifier.getNotifier();

		// 创建无阻塞网络套接
		selector = Selector.open();
		ssc = ServerSocketChannel.open();

		InetSocketAddress address = new InetSocketAddress(port);
		ssc.socket().bind(address);
		Debug.logVerbose("-->Start host:" + InetAddress.getLocalHost()
				+ " port=" + port);

		ssc.configureBlocking(false);
		// 向selector注册该channel
		@SuppressWarnings("unused")
		SelectionKey sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
	    //利用sk的attache功能绑定Acceptor 如果有事情,触发Acceptor
	    sk.attach(new Acceptor(selector, ssc));

		Debug.logVerbose("-->TCP Server started");
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		int num = 0;
		// 监听
		while (!Thread.interrupted()) {
			try {
				num = selector.select();

				if (num > 0) {
					Set<SelectionKey> selectedKeys = selector.selectedKeys();
					Iterator<SelectionKey> it = selectedKeys.iterator();
					while (it.hasNext()) {
						SelectionKey key = (SelectionKey) it.next();
						it.remove();
						dispatch(key);
						selectedKeys.clear();
					}
				} 
			} catch (Exception e) {
				notifier.fireOnError("-->Error occured in Server: "
						+ e.getMessage());
				continue;
			}
		}
	}

	private void dispatch(SelectionKey key) throws Exception {
		Runnable r = (Runnable) (key.attachment());
		if(r != null){
			r.run();
		}
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -