1
votes

I have to implement a client for communication with the server by custom protocol based on XML format. This is an application layer protocol, based on TCP. So, my client sends a request XML message and receives a response, also XML message. Now, I consider how to be ensured that I received whole mesage before I start parsing it.

I see two aproaches:

  1. Receiving bytes to the some magic number that means end of message. It is the best approch (for my eye), yes?

  2. But, it is possible that there is no magic number and size of message is not known. What about that case? I saw some clients for other protocols and I see something like that.

    while(true){
        r = socket.read(buffer, offset, 1024);
        if(r < 1024) break;
        offset += r;
    }
    // parse buffer
    

and I am not sure whether it is ok. It assumes that if we read less than 1024 bytes then the messae is completed. Is it ok?

What is a recommend way to solve it?

1
That is not a custom tcp protocol. You're simply reading from a Socket's InputStream. Take a look at what the different read methods do.f1sh
If you can control the spec to add magic numbers, why not just switch to Rest? Its basic form is XML based, you'd likely have few changes, and the whole problem you have now would just disappear. (But likely what you want to do is read until end of stream.)markspace
EDIT: but the loop of code you show above is dead wrong. Please use Google and find something better.markspace
take advice from http (tools.ietf.org/html/rfc7230#section-3.3.3) - have the client send the length of the content before the content itselfjamey graham

1 Answers

0
votes

In your custom protocol you need to include the steps below :

Client

  1. Calculate number of 1024 byte chunks of the XML contents i.e ceiling(XML content bytes /1024)
  2. Send the number of step 1 to the server through the socket
  3. Transmit the contents in chunks of a defined buffer size e.g 1024 bytes

Server

  1. Read number of chunks to receive from client

  2. Inside a for loop of size equal to the number read at step 1, start receiving contents in the predifined buffer size.

This way the server knows how many bytes the actual content is before it starts receiving the XML contents.