带java选择器的无限循环
我是Java的新手,现在我对Java nio选择器感到困惑,下面是Java网络程序第三册中的代码带java选择器的无限循环,java,selector,nio,Java,Selector,Nio,我是Java的新手,现在我对Java nio选择器感到困惑,下面是Java网络程序第三册中的代码 package org.eclipse.java.socket.samples; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey;
package org.eclipse.java.socket.samples;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class ChargenServer {
public static int DEFAULT_PORT = 4321;
public static void main(String[] args) {
int port;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
port = DEFAULT_PORT;
}
System.out.println("Listening for connections on port " + port);
byte[] rotation = new byte[95 * 2];
for (byte i = ' '; i <= '~'; i++) {
rotation[i - ' '] = i;
rotation[i + 95 - ' '] = i;
}
ServerSocketChannel serverChannel;
Selector selector;
try {
serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = new InetSocketAddress(port);
ss.bind(address);
serverChannel.configureBlocking(false);
selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
catch (IOException ex) {
ex.printStackTrace();
return;
}
while (true) {
try {
selector.select();
}
catch (IOException ex) {
ex.printStackTrace();
break;
}
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
SocketChannel client = server.accept();
System.out
.println("Accepted connection from " + client);
client.configureBlocking(false);
SelectionKey key2 = client.register(selector,
SelectionKey.
OP_WRITE);
ByteBuffer buffer = ByteBuffer.allocate(74);
buffer.put(rotation, 0, 72);
buffer.put((byte) '\r');
buffer.put((byte) '\n');
buffer.flip();
key2.attach(buffer);
}
else if (key.isWritable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
if (!buffer.hasRemaining()) {
// Refill the buffer with the next line
buffer.rewind();
// Get the old first character
int first = buffer.get();
// Get ready to change the data in the buffer
buffer.rewind();
// Find the new first characters position in
// rotation
int position = first - ' ' + 1;
// copy the data from rotation into the buffer
buffer.put(rotation, position, 72);
// Store a line break at the end of the buffer
buffer.put((byte) '\r');
buffer.put((byte) '\n');
// Prepare the buffer for writing
buffer.flip();
buffer.compact();
}
client.write(buffer);
}
}
catch (IOException ex) {
key.cancel();
try {
key.channel().close();
}
catch (IOException cex) {
}
}
}
}
}
}
在我的理解中,“selector.select()”等待来自远程服务器的输入事件,然后它.remove()删除此事件,因此选择器开始等待来自远程服务器的新事件,这样客户端就可以使用选择器连续地从服务器获取数据,但结果是一次又一次循环的,选择器对服务器的数据毫无意义,
为什么?
我的代码有问题吗 一旦您写入了所需的所有内容(即,当输出缓冲区为空时),您应该删除
OP\u WRITE
interest标志。三个是与代码相关的多个问题,包括不关闭选择器
只有在写入操作无法写入整个缓冲区时,才需要注册OP_WRITE
,否则需要取消注册。查看interestedOps()
通常,您需要OP_READ才能从该频道读取。
最后,总是在stackoverflow之前检查(这是我跟踪的bug之一)。建议:不要使用相同的选择器来接受/写入
干杯我怀疑您的连接总是准备好写入,或者是时候让调试器出来看看发生了什么。就我个人而言,我在NIO中使用阻塞,而不是使用选择器,这使代码更加简单。(可以更快)阻塞非常简单,但当我需要管理多个连接时,选择器是一个完美的选择,而不是多个线程。您需要关闭与finally Blocks的连接,但我需要一个连续连接…您想通过套接字连接侦听particuler端口上的数据。。?
package org.eclipse.java.socket.selector;
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;
import java.util.Set;
public class SocketSelector {
public static void main(String[] args) throws IOException {
// Create selector
Selector selector = null;
selector = Selector.open();
////////////////////////////////////////////////////////////////////////
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(
"localhost", 4321));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_CONNECT);
/*
* Let's begin select
*/
while (true) {
selector.select();
System.out.println("Hello, selector!");
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey )it.next();
if (key.isReadable()) {
System.out.println("It's readable!");
}
it.remove();
}
}
}
}