为什么注册到DatagramChannel的SelectionKey会返回Scala中的SelectableChannel但不返回Java?

时间:2010-01-25 20:49:56

标签: java scala nio casting

我正在转换一些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);
// ...

1 个答案:

答案 0 :(得分:2)

SelectionKey.channel()始终返回SelectableChannel。此时指定的频道类型并不真正相关,因此您必须进行投射。