简体   繁体   中英

How to make Java send multiple messages together?

Here's an extract of my code:

OutputStream out = this.socket.getOutputStream();
out.write(fourBytes);
out.write(someBytes);
out.flush();

This gets sent in 2 packages, even though the first one is only 4 bytes long. Is there another way than concatenating the byte arrays together to send them together?

I've already tried setTcpNoDelay(false) .

Sure. Use a BufferedOutputStream . :-P

The setTcpNoDelay changes how the OS sends packets, not how Java sends packets. The only way to change the latter is to buffer your output, as I suggested above.

BTW, this doesn't affect how many packets your data is really split up into. Again, that is up to the OS, as well as the window specified by the receiving end. So you can't use packets to delimit data.

Wrap it with buffered output stream

I think disabling Nagle is done by setTcpNoDelay(true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM