2

I'm using an ObjectOutputStream over my socket because I created a new class that needs to be transported between the client and the server. I also created a unique thread that sends one byte every one second over the stream to the server in order to inspect the connection continuously and check that its alive.

byte b=1;
oos.writeObject(b);

I use "byte" because it is the smallest object that I can send (right?) so that the server will not read longer objects.

My question is if the server reads one byte object (size of byte) or an 8 byte object (the size of an object) ?

Onca
  • 1,113
  • 3
  • 17
  • 31
  • A byte is *not* the smallest object you can send; a bit is. A byte consists of 8 bits. Booleans are equivalent to bytes. Using `writeObject` will result in the class, class signature, and serializable fields to be written to the stream as well, so the size will vary; I recommend testing that out on your own for the case of a Byte object. – FThompson Sep 04 '12 at 21:39
  • Do you mean an object size is 8 byte? – Roman C Sep 04 '12 at 21:42
  • Unfortunately you cannot send/receive one bit in Java. The best thing you can do is pack 8 separate bits into a byte and send that one byte and unpack the bits on the other side, which can be used to send up to 8 true/false (1/0) values in one byte instead of 8 bytes of values 1 or 0. – Blake Beaupain Sep 06 '12 at 20:54

2 Answers2

2

Probably neither. First, a byte is autoboxed into a Byte. Then the Byte is serialized to your output stream. It probably takes quite a bit more than 8 bytes to send. I don't know the spec exactly, but it probably sends the class name java.lang.Byte and the byte itself, plus probably a few more control bytes.

An easy way to tell - serialize your byte to a ByteArrayOutputStream, flush your ObjectOutputStream, then see how many bytes your ByteArrayOutputStream ends up with.

Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • `writeObject` sends the class name, class signature, the object's serializable values, and stream headers. You are correct on saying "neither", so +1. – FThompson Sep 04 '12 at 21:48
1

If you must use an ObjectOutputStream, it really doesn't matter which object you send because after the first one is sent, a reference to that object will be sent in the future. For this reason I suggest you send a specific enum like.

enum Control {
    HEARTBEAT
}

You could make the wire format much smaller using DataOutputStream where 1 byte is one byte. Given the IP packet header is about 20 bytes, it doesn't really matter whether you send 1 byte or 8 bytes as the overhead is much higher than this.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130