我在使用时遇到CPU使用问题
java.nio.channel.Selector
。
当服务器线程启动时,它最初消耗200%的cpu资源并大幅下降到0.1%。但如果它是由客户连接的。这个数字迅速增加到97% - 100%并且即使在客户端断开连接之后也保持这个数字。
这是我为服务器编写的代码。
package com.cs.gang.test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
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;
public final class TCPConnectionServer implements Runnable {
private RandomAccessFile logFile;
private Selector selector;
public TCPConnectionServer() throws IOException {
final File logFile = new File("server_log.txt");
if (logFile.exists()) {
logFile.delete();
}
this.logFile = new RandomAccessFile(logFile.getCanonicalPath(), "rw");
System.out.println(logFile.getCanonicalPath());
selector = Selector.open();
final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
@Override
public void run() {
while (true) {
try {
if (selector.select() > 0) {
final Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
final SelectionKey key = keys.next();
keys.remove();
if (key.channel() instanceof SocketChannel) {
if (!((SocketChannel) key.channel()).isConnected()) {
logFile.writeChars(((SocketChannel) key.channel()).toString() + " is off line");
}
}
if (key.isAcceptable()) {
final ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
final SocketChannel clientChannel = serverSocketChannel.accept();
clientChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
logFile.writeChars(clientChannel.toString() + "is now connected");
} else if (key.isReadable()) {
final SocketChannel client = (SocketChannel) key.channel();
if (client.isConnected()) {
final ByteBuffer buffer = ByteBuffer.allocate(1024);
int byteRead = -1;
final StringBuilder sb = new StringBuilder(client.toString()).append(" : ");
while ((byteRead = client.read(buffer)) > 0) {
sb.append(new String(buffer.array()), 0, byteRead);
buffer.clear();
}
logFile.writeChars(sb.toString());
System.out.println(sb.toString());
} else {
System.out.println("Closed Connection detected");
}
}
}
} else {
System.out.println("Sleep for 100ms");
Thread.sleep(100);
}
} catch (final IOException e) {
e.printStackTrace();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new Thread(new TCPConnectionServer()).start();
}
}
任何人都可以帮助我吗?我是NIO的新手,我现在完全不知道这个问题。
由于
答案 0 :(得分:4)
clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
问题出在这里。 OP_WRITE
几乎总是准备就绪,因此您的选择器很少会阻塞并且通常会旋转。这是对OP_WRITE
的误用。使用它的正确方法如下:
write()
返回零,则注册OP_WRITE
的套接字并返回选择循环。当然,您还必须保存您正在撰写的ByteBuffer
与频道相关联:这通常是通过SelectionKey
的附件直接或间接完成的。理想情况下,每个频道都有一个读取和写入ByteBuffer
,保存在频道上下文对象中,而后者又保存为关键附件。OP_WRITE
触发时,继续写ByteBuffer.
如果完成,即write()
没有返回零或短写入次数, de - 注册OP_WRITE.