Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Java send multiple messages together?

Tags:

java

sockets

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).

like image 747
Georg Schölly Avatar asked Jan 27 '26 06:01

Georg Schölly


2 Answers

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.

like image 185
Chris Jester-Young Avatar answered Jan 28 '26 18:01

Chris Jester-Young


Wrap it with buffered output stream

like image 30
Ramesh PVK Avatar answered Jan 28 '26 18:01

Ramesh PVK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!