我在Java中构建了一个基于Selector的系统,可以接受多个客户端。它有一个在OP_ACCEPT下注册的ServerSocketChannel,它接受()s传入连接并再次向选择器注册生成的SocketChannel。这就是:
ServerSocketChannel insock = ServerSocketChannel.open();
insock.configureBlocking(false);
insock.socket().bind(new InetSocketAddress(6789));
Selector sel = Selector.open();
SelectionKey joinchannel = insock.register(sel, SelectionKey.OP_ACCEPT);
System.out.println("Ready to accept incoming connections.");
while (true) {
int ready = sel.selectNow();
if (ready == 0)
continue;
Set<SelectionKey> selectedKeys = sel.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()){
SocketChannel newConnection = insock.accept();
System.out.println("New client "+newConnection+" connected.");
newConnection.configureBlocking(false);
newConnection.register(sel, SelectionKey.OP_READ).attach(new DGPlayer());
}
如果我为OP_READ注册新的SocketChannel,这样可以正常工作。检查isReadable()成功,读取数据。这就是:
else if(key.isReadable()){
ByteBuffer buf = ByteBuffer.allocate(1024);
int trans = ((SocketChannel)key.channel()).read(buf); buf.flip();
byte[] ba = new byte[buf.remaining()]; buf.get(ba);
String msg = new String(ba, 0, ba.length, Charset.forName("UTF-8"));
if(trans > 0){
DGPlayer client = (DGPlayer) key.attachment();
System.out.println(client.name+": "+msg.trim());
}
}
// else if(key.isWritable()){
// ByteBuffer buf = ByteBuffer.allocate(48);
// buf.clear();
// buf.put(((String)key.attachment()).getBytes());
// buf.flip();
//
// SocketChannel target = ((SocketChannel)key.channel());
// while(buf.hasRemaining()) {
// target.write(buf);
// }
//
// key.attach(null);
// }
但是,如果我为OP_READ | OP_WRITE注册SocketChannel,则没有任何反应。据我所知,选择器永远不会发现通道是可读的()或可写的()。唯一的变化是注册通道以获得WRITE权限。
知道为什么会这样吗?
编辑 - 为了完成,这里有一些客户端代码:
while (true) {
int readyChannels = sel.select();
if (readyChannels == 0)
continue;
Set<SelectionKey> selectedKeys = sel.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isReadable()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
int trans = ((SocketChannel)key.channel()).read(buf); buf.flip();
byte[] ba = new byte[buf.remaining()]; buf.get(ba);
String msg = new String(ba, 0, ba.length, Charset.forName("UTF-8"));
if(msg.trim().length() != 0)
System.out.println("Response from server: "+msg.trim());
}
else if(key.isWritable() && messages.size() > 0){
String message = messages.remove();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(message.getBytes(Charset.forName("UTF-8")));
buf.flip();
int written = outsock.write(buf);
while(buf.hasRemaining()){
outsock.write(buf);
}
System.out.println("Wrote '"+message+"' to server");
}
keyIterator.remove();
}
}
(客户端为OP_READ | OP_WRITE注册服务器)
答案 0 :(得分:7)
一般来说,如果你没有任何东西可以主动写入,那么为OP_WRITE
注册一个频道是个坏主意。大多数时间都可以写入大多数频道,因此每次调用Selector.select
都会无阻塞地返回并消耗资源。当您准备好向频道写入内容时,最好将写入标记添加到SelectionKey.interestOps
,并在完成后删除该标记。