javasocketsstream

How can I know what l am reading with Java Sockets?


I'm creating a Java Application which needs the Client to communicate (Send & Receive data) with other Clients. I have made a simple Server Application to make Client communication easier.

To communicate, Server & Client use a Class that I have created named "Request". First, I was thinking that a Simple ObjectOutputStream/InputStream will be able to send/receive my Request Object and it is! But I have changed my plans:

Now, I serialize my Request Object as a byte array and I encrypt it with Cipher. I already made the decryption & deserialization method, but I don't know how to read byte array corresponding to the request. After having searched, I found that to know how many bytes I have to read, I have to send a int with the byte array length. I also found that a ByteArrayOuputStream/InputStream exists, is it adapted for me? And how to read/write the totality of a byte array?


Solution

  • On the sending side, write the length of the byte array first and then the actual byte array:

    OutputStream os = ...;
    byte[] data = ...;
    int dataLength = data.length;
    os.write(dataLength >> 24);
    os.write(dataLength >> 16);
    os.write(dataLength >> 8);
    os.write(dataLength);
    os.write(data);
    

    On the receiving side, read the first four bytes, reconstruct the data length and then read the appropriate number of bytes from the input stream:

    InputStream is = ...;
    byte[] buf = new byte[4];
    is.read(buf);
    int dataLength = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
    // read rest of data according to dataLength
    

    Note: The above code snippets don't include necessary sanity checks!