📄 tcpreactor.java
字号:
/**
* Created at Nov 10, 2008
*/
package com.jdev.net.tcp;
import java.net.*;
import java.nio.channels.*;
import java.util.*;
import java.io.*;
/**
* <p>Title: TCPReactor</p>
* <p>Description: 服务器事件监听器</p>
* @author Lawrence
* @version 1.0
*/
public class TCPReactor implements Runnable {
private final static String module = TCPReactor.class.getName();
/**
* Selector 实例
*/
private final Selector selector;
/**
* SelecableChannel 实现
*/
private final ServerSocketChannel sc;
private int PORT = 8009;
/**
*
*/
public TCPReactor() throws IOException {
/**
* 创建Selector实例
*/
selector = Selector.open();
/**
* 创建ServerSocketChannel实例
*/
sc = ServerSocketChannel.open();
Init();
}
public TCPReactor(int port) throws IOException{
PORT = port;
/**
* 创建Selector实例
*/
selector = Selector.open();
/**
* 创建ServerSocketChannel实例
*/
sc = ServerSocketChannel.open();
Init();
}
private void Init() throws IOException{
/**
* 绑定ServerSocketChannel
*/
InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(),PORT);
sc.socket().bind(address);
/**
* 设置非堵塞
*/
sc.configureBlocking(false);
/**
* 注册监听事件为SelectionKey.OP_ACCEPT
*/
SelectionKey sk = sc.register(selector, SelectionKey.OP_ACCEPT);
/**
* 绑定处理事件
*/
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
try{
/*
* 检查是否触发select key
*/
while(!Thread.interrupted()){
selector.select();
Set selected = selector.selectedKeys();
Iterator it = selected.iterator();
/*
* 如果发现channel有事件,则遍历key
*/
while(it.hasNext()){
}
}
}
catch(IOException ex){
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -