本文介绍了Java NIO。 SocketChannel.read方法一直返回0.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着了解java NIO是如何工作的。特别是,如何工作SocketChannel。

I try understand how works java NIO. In particular, how works SocketChannel.

我在下面写了代码:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;

public class Test {

    public static void main(String[] args) throws IOException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("google.com", 80));

        while (!socketChannel.finishConnect()) {
            // wait, or do something else...
        }

        String newData = "Some String...";

        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());

        buf.flip();

        while (buf.hasRemaining()) {
            System.out.println(socketChannel.write(buf));
        }

        buf.clear().flip();

        int bytesRead;

        while ((bytesRead = socketChannel.read(buf)) != -1) {

            System.out.println(bytesRead);

        }

    }

}




  1. 我尝试连接到谷歌服务器。

  2. 向服务器发送请求;

  3. 阅读答案来自服务器。

但是,方法socketChannel.read(buf)始终返回0并无限执行。

but, method socketChannel.read(buf) all time return 0 and performs infinitely.

我犯了错误?

推荐答案

因为 NIO SocektChannel 在数据可供读取之前不会阻止。即,非阻塞频道可以在read()操作上返回0

Because NIO SocektChannel will not block until the data is available for read. i.e, Non Blocking Channel can return 0 on read() operation.

这就是为什么在使用NIO时你应该使用如果数据可用,它会在通道上提供读取通知。

That is why while using NIO you should be using java.nio.channels.Selector which gives you read notification on channel if the data is available.

另一方面,阻塞通道将等待数据可用并返回多少数据可用。即,阻止频道永远不会在read()操作上返回0

On the otherhand, blocking channel will wait till the data is available and return how much data is available. i.e, Blocking channel will never return 0 on read() operation.

你可以阅读更多关于NIO在这里:





  • http://tutorials.jenkov.com/java-nio/index.html
  • http://java.sun.com/developer/technicalArticles/releases/nio/
  • https://www.ibm.com/developerworks/java/tutorials/j-nio/section2.html

这篇关于Java NIO。 SocketChannel.read方法一直返回0.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:34