e174. reading from a socketchannel.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 25 行

TXT
25
字号
See also e173 Creating a Non-Blocking Socket. 
    // Create a direct buffer to get bytes from socket.
    // Direct buffers should be long-lived and be reused as much as possible.
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    
    try {
        // Clear the buffer and read bytes from socket
        buf.clear();
        int numBytesRead = socketChannel.read(buf);
    
        if (numBytesRead == -1) {
            // No more bytes can be read from the channel
            socketChannel.close();
        } else {
            // To read the bytes, flip the buffer
            buf.flip();
    
            // Read the bytes from the buffer ...;
            // see e159 Getting Bytes from a ByteBuffer
        }
    } catch (IOException e) {
        // Connection may have been closed
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?