我决定用 java nio 制作我的 UDPclient 和 UDPserver。但我不明白几件事。这是代码
try {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(remote);
//monitoring
Selector selector = Selector.open();
//read write keys
channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024*64);//number of bytes for channel
while (true) {
selector.select(60000);//number of channels I think
Set readyKeys = selector.selectedKeys();
if (readyKeys.isEmpty()) {
break;
}
else {
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (key.isReadable( )) {
//read from buffer
channel.read(buffer);
}
if (key.isWritable()) {
//write to buffer
channel.write(buffer);
}
}
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
如果我在控制台中写一些东西,事件key.isWritable
会发生吗?如果服务器发送一些事件 isReadable 会发生吗?当例如用户编写“GETL”或“REGR”(我自己的方法)时,我不明白如何处理我的事件。