search

Home  >  Q&A  >  body text

java socket read 阻塞问题???

自己写了一个小的服务器代码,从socket中读取数据时,用读一次的方式就不会阻塞,而放在while里面就会阻塞为什么呢?如果read是阻塞的,那么即使是读一次也因该会被阻塞啊?
代码如下:

in.read(buffer);
for(byte b : buffer)
    request.append((char)b);

这是读一次的方法,不会阻塞。

   while((len = in.read(buffer)) != -1){
        for(byte b : buffer){
            request.append((char)b);
    }

这是while循环的方法,会被阻塞。
求解啊!!

PHPzPHPz2889 days ago415

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:49:23

    The following is the explanation of the read method from the Java API documentation:

    This method blocks until input data is available, end of file is detected, or an exception is thrown.

    It means that read will block when no new data can be read.

    When placed in the while read, if the client sends data, then the read will not block and will read the data sent by the client into the array. The loop will continue until the second time when the client does not send data to the server again, then the server will read If it cannot be retrieved, it will keep waiting for the client's data, which will block it.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:49:23

    Everything will be blocked, but you won’t feel it if you only read it once. while的使用具体看处理的方式,一般使用while是为了无限读取,也就是监听连接的效果。而在监听读取中,会拟定一些传输协议,通过传输协议来确定单条消息的结束点,当读到结束点时就提交给处理程序处理。使用readWhen reading, the content will not be automatically divided into single messages when reading, but all the content will be continuously read, so as long as the other end does not send a message, this side will always be blocked.

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:49:23

    It is inherently blocked. It is recommended to put the server into a multi-thread. After blocking, directly create a thread and put the read data into the thread. Let the thread handle it, so you can request multiple requests.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:49:23

    The key is: while((len = in.read(buffer)) != -1), as long as the socket is not closed, this while will not exit, and your above code just reads the content into the buffer, so The read method reads the size of the buffer and returns it. Your two programs have nothing to do with blocking, because if read cannot read and the socket is not closed, it will block.

    reply
    0
  • Cancelreply