虽然我们可以自己处理每一个Socket事件,比如读写数据,不过更常规的方式是注册一个选择器。这个选择器侦听着数据的变化事件。 每个注册的通道都有自己的SelectionKey,用这个可以区分到底是哪个通道产生了事件。
看代码
package net.java2000.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* 多个SocketChannel注册Selector。
*/
public class SocketChannelSelector {
public static SocketChannel createSocketChannel(String hostName, int port)
throws IOException {
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
// 2个连接注册的选择器关键字
static SelectionKey key1;
static SelectionKey key2;
public static void main(String[] args) {
// 1个选择器,注册2个Socket 通道
Selector selector = null;
try {
// 创建选择器
selector = Selector.open();
// 创建2个通道
SocketChannel sChannel1 = createSocketChannel("163.net", 25);
SocketChannel sChannel2 = createSocketChannel("mail.csdn.net", 25);
// 注册选择器,侦听所有的事件
key1 = sChannel1.register(selector, sChannel1.validOps());
key2 = sChannel2.register(selector, sChannel1.validOps());
} catch (IOException e) {
}
// 青年人网站提示等待事件的循环
while (true) {
try {
// 等待
selector.select();
} catch (IOException e) {
break;
}
// 所有事件列表
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
// 处理每一个事件
while (it.hasNext()) {
// 得到关键字
SelectionKey selKey = it.next();
// 删除已经处理的关键字
it.remove();
try {
// 处理事件
责任编辑:小草