Question

I have a client program and a server program. I send 512-byte packets, and I want to send some files. How can the server know when the transmission is finished?

I want the server program to receive some files before it stops running, and I want to distinguish between them. What I want to do is print out the number of packet received:

Packet number 1 has been received

Packet number 2 has been received

.

.

Packet number N has been received

And once I receive this file, I want to set this counter variable to 0, which means that I have to detect when a file is completely sent (it means to receive less than 512 bytes). Is there any way to count the amount of bytes received from the client program? Which is the best way to do it? I am using byte arrays.

Was it helpful?

Solution

The best way to do it is to introduce a delimiter. This will become part of your protocol.

When you're sending the files, you send the data. When there are no more bytes to sends, the client will send an END_OF_MESSAGE value to the server, indicating that there is no more data to send, then in your code, you've got something like:

String END_OF_MESSAGE = "ENDOFMESSAGE";

if(input.equals(END_OF_MESSAGE)) {
    // You know the client has finished their transmission.
}

NOTE: I would make the value of END_OF_MESSAGE far more complex than that. This is simply for demonstration purposes.

EDIT

As JB Nizet suggested, another option is to send the length of the file before anything else. That way the server knows when the transmission is finished when the amount of transferred bytes are equal to, or greater than, the pre-set size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top