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

后端 未结 4 858
感情败类
感情败类 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: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);
    }
    

提交回复
热议问题