Java: Are concurrent reads and writes possible on a blocking SocketChannel via Object(In|Out)putStreams?

后端 未结 4 857
感情败类
感情败类 2021-02-08 17:28

I created an ObjectInputSteam and ObjectOutputStream on a blocking SocketChannel and am trying to read and write concurrently. My code is

相关标签:
4条回答
  • 2021-02-08 18:13

    If you want to use InputStream and OutputStream concurrently with SocketChannel, from looking at the source, it appears that you need to call SocketChannel.socket() and use the streams from that which behave slightly differently.

    0 讨论(0)
  • 2021-02-08 18:25

    The workaround in the bug report worked for me. It's worth noting that only one of input or output needs to be wrapped for the workaround to work - so if performance is especially important in one direction then you can wrap the less important one and be sure that the other will get all the optimisations available to it.

    public InputStream getInputStream() throws IOException {
        return Channels.newInputStream(new ReadableByteChannel() {
            public int read(ByteBuffer dst) throws IOException {
                return socketChannel.read(dst);
            }
            public void close() throws IOException {
                socketChannel.close();
            }
            public boolean isOpen() {
                return socketChannel.isOpen();
            }
        });
    }
    
    public OutputStream getOutputStream() throws IOException {
        return Channels.newOutputStream(socketChannel);
    }
    
    0 讨论(0)
  • 2021-02-08 18:25

    Interesting bug! You say though that you can't use FileChannel#transferTo. How about wrapping the I/O streams of the non-NIO socket into channels using Channesl#newChannel before passing to FileChannel#transferTo?

    0 讨论(0)
  • 2021-02-08 18:27

    This seems to be a bug in java.nio.channels.Channels (thanks to Tom Hawtin; post it as an answer next time). A good description and workaround are described here (actually a duplicate of the bug Tom listed):

    I tested the workaround and it works.

    0 讨论(0)
提交回复
热议问题