开发者

Why does a SelectionKey registered to a DatagramChannel return a SelectableChannel in Scala but not Java?

开发者 https://www.devze.com 2022-12-17 21:39 出处:网络
I am converting some Java NIO code to run in Scala and I am getting an error because the SelectionKey I\'m calling returns a SelectableChannel rather than a DatagramChannel, which is a subclass of Sel

I am converting some Java NIO code to run in Scala and I am getting an error because the SelectionKey I'm calling returns a SelectableChannel rather than a DatagramChannel, which is a subclass of SelectableChannel and an instance of which I declare at the beginning of the code. I did not come to Scala from Java, so my knowledge of Java is actually very limited. It seems to me that the Java code DatagramChannel channel = (DatagramChannel) key.channel(); typecasts the channel to a DatagramChannel. Is this what I need to do in the Scala code?

Scala code:

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);
// ...

Original Java code:

channel = DatagramChannel.open();
selector = Selector.ope开发者_开发问答n();
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() always returns a SelectableChannel. The assigned type of the channel is not really relevant at this point, so you'll have to cast it.

0

精彩评论

暂无评论...
验证码 换一张
取 消