BullyWiiPlaza
BullyWiiPlaza

Reputation: 19185

Wait For Socket Data Transmission

I'm using a DataOutputStream to transmit data over the network like this:

Socket socket = new Socket(ipAddress, port);
DataOutputStream dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());

dataOutputStream.writeBytes("Stackoverflow");
// ...
System.exit(0);

If my application terminates too early, the transmission will be aborted and therefore fail since not all data has been sent yet at that point.

To fix this, I could manually wait for some time before terminating:

try
{
    Thread.sleep(1000);
} catch (InterruptedException e)
{
    e.printStackTrace();
}

However, this solution is bad. Are there some "best practice" ways of assuring that all data has been sent before terminating my application?

Edit:
I don't have access to the server code.

Upvotes: 1

Views: 1519

Answers (3)

Koustuv Ganguly
Koustuv Ganguly

Reputation: 899

Set socket.setSendBufferSize(1024) also make sure while receiving there you read in chunk of 1024 bytes.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

If my application terminates too early, the transmission will be aborted and therefore fail since after the execution of flush() not all data has been sent yet.

The data is unbuffered so every write sends the data immediately. In your case the flush() isn't doing anything.

DataOutputStream.flush()

public void flush() throws IOException {
    out.flush();
}

calls OutputStream.flush()

public void flush() throws IOException {
}

Are there some "best practice" ways of assuring that all data has been sent before terminating my application?

The best way to ensure the data has been sent is to wait for a reply. Have the other end send a message back to say it has received it and you can exit knowing the data has been received.

BTW When you have finished with a closeable resources, best practice is to close it.

Upvotes: 1

SKi
SKi

Reputation: 8466

By the default socket.close() should cause graceful TCP connection closing. In that procedure TCP stack delivers unacknowledged data to the peer.

dataOutputStream.flush();
socket.close();

if you have set SO_LINGER to zero, then it won't work. Alternative is to use socket.shutdownOutput():

dataOutputStream.flush();
socket.shutdownOutput();

Upvotes: 0

Related Questions