I created an ObjectInputSteam
and ObjectOutputStream
on a blocking SocketChannel
and am trying to read and write concurrently. My code is
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.
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);
}
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?
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.