Sockets to send/recieve bytes - best reader/writer?

Hi guys,

I was looking for the best solution to send/recieve bytes and never found a great solution. The best one I found (and which works unless the socket calls come in a different order than sent) is the following:

Send:

DataOutputStream socketWriter;
try {
    socketWriter.writeInt(message.length);
    socketWriter.write(message);
} catch (IOException e) {
    e.printStackTrace();
}

Receive:

DataInputStream socketReader;
byte[] b=null;
String message=null;
int size;
try {
    size=socketReader.readInt();
    b=new byte[size];
    socketReader.readFully(b);
} catch (IOException e) {
    e.printStackTrace();
}

The problem is that readFully needs to know how many bytes it should read. One way to solve this is to always let the server wait for a confirmation that the client got the whole message (both the int and the bytearray) before sending the next message but there should be a better way to do this, or?

Thanks,
Mike

I don’t quite understand the problem, why would the server need to wait for confirmation that the client has received the whole message? If this is being sent reliably (TCP) you can send the client all the bytes you please and as long as the connection remains established you are garanteed they will receive them in the order they were sent. I don’t really see any need for the client to ACK the message as being received. On the client you just parse off each message as it comes. In your case read the message length and then read the message of that length. If you are using non blocking operations you may need to buffer data until the whole message is available to you.

Indeed, what you are doing is correct.

But please add some sanity-check on the value of readInt(), as it’s now way too easy to hijack all RAM in the server.

So if I send different messages really quick I’m always sure that each message will arrive in the same order? That solved my potential problem, thanks :slight_smile:

Riven, that makes perfect sense and I’m adding it right away, thanks! :slight_smile:

I love this forum. The most helpful and friendly people ever! :smiley:

Yes provided that you are using a reliable transport such as TCP this is guaranteed!