![](/img/trans.png)
[英]C# classes for SelectionKey, SelectableChannel and Selector in Java?
[英]Why does a SelectionKey registered to a DatagramChannel return a SelectableChannel in Scala but not Java?
我正在转换一些Java NIO代码以在Scala中运行,但由于我正在调用的SelectionKey返回的是SelectableChannel而不是DatagramChannel(它是SelectableChannel的子类,而我在该代码的开头声明了一个实例)而收到错误,码。 我不是从Java来的Scala,所以我对Java的了解实际上非常有限。 在我看来,Java代码DatagramChannel channel = (DatagramChannel) key.channel();
将频道类型转换为DatagramChannel。 这是我在Scala代码中需要做的吗?
Scala代码:
val channel = DatagramChannel.open()
val selector = Selector.open()
println("Attempting to bind to socket " + port)
channel.socket().bind(new InetSocketAddress(port))
println("Bound to socket " + port)
channel.configureBlocking(isBlocking)
println("Attempting to registered selector")
channel.register(selector, SelectionKey.OP_READ)
println("Registered selector")
println("Ready to receive data!");
while (true) {
try {
while(selector.select() > 0) {
val keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
val key = keyIterator.next();
if (key.isReadable()) {
val channel = key.channel(); // FIXME: returning a SelectableChannel instead of a DatgramChannel
var buffer: Array[Byte] = Array();
val byteBuffer = ByteBuffer.wrap(buffer);
val sockAddress = channel.receive(byteBuffer);
// ...
原始Java代码:
channel = DatagramChannel.open();
selector = Selector.open();
System.out.println("Attempting to bind to socket " + port);
channel.socket().bind(new InetSocketAddress(port));
System.out.println("Bound to socket " + port);
channel.configureBlocking(isBlocking);
System.out.println("Attempting to registered selector");
channel.register(selector, SelectionKey.OP_READ);
System.out.println("Registered selector");
System.out.println("Ready to receive data!");
while (true) {
try {
while(selector.select() > 0) {
Iterator keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = (SelectionKey) keyIterator.next();
if (key.isReadable()) {
DatagramChannel channel = (DatagramChannel) key.channel();
byte[] buffer = new byte[2048];
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
SocketAddress sockAddress = channel.receive(byteBuffer);
// ...
SelectionKey.channel()始终返回SelectableChannel 。 在这一点上,通道的分配类型实际上并不重要,因此您必须强制转换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.