I've tried to increase the send buffer size of a SocketChannel. I want to send all the bytes in my ByteBuffer in only one write operation. This is my code:
channel = SocketChannel.open(address);
ByteBuffer buf = ByteBuffer.wrap(channelBytes);
channel.socket().setSendBufferSize(buf.remaining());
channel.write(buf);
Even if I call the method setSendBufferSize, the socket doesn't send more than 131071 bytes. How can I do?
The receiver is this:
Constructor
uplink = ServerSocketChannel.open();
uplink.socket().bind(new InetSocketAddress(UPLINK_PORT));
uplink.socket().setReceiveBufferSize(2*1024*1024);
Run method
SocketChannel clientChannelUp = uplink.accept();
clientChannelUp.socket().setReceiveBufferSize(2*1024*1024);
clientChannelUp.socket().setSendBufferSize(2*1024*1024);
buffer = ByteBuffer.allocate(Short.MAX_VALUE*100);
clientChannelUp.read(buffer);
buffer.flip();
With the read and write loop my code is this:
transmitter
while(buf.hasRemaining()) {
channel.write(buf);
}
receiver
int r = clientChannelUp.read(buffer);
while(r==131071) {
r=clientChannelUp.read(buffer);
}
buffer.flip();
The code you have posted blocks until all the data has been transferred into the socket send buffer, independently of the socket send buffer size. Your own experiments prove that. You didn't set it to 131071, left it at 8192, and yet 131071 bytes were still received.
What you mean is that the peer doesn't receive more than 131071 bytes.
That's because of the size of its socket receive buffer.
To set a socket receive buffer size larger than 64k it needs to be set before the socket is connected. In the case of a server, that means setting it in the ServerSocket
or ServerSocketChannel
before calling accept()
.
However your basic objective isn't realizable. TCP is a byte stream protocol. It isn't obliged to deliver more than one byte at a time, or zero in non-blocking mode. If you want to receive N bytes, in general you have to loop.