开发者

Socket output stream with DataOuputStream - what are the guarantees?

开发者 https://www.devze.com 2023-03-28 01:43 出处:网络
Looking at the code: private static void send(final Socket socket, final String data) throws IOException {

Looking at the code:

private static void send(final Socket socket, final String data) throws IOException {
    final OutputStream os = socket.getOutputStr开发者_如何学Goeam();
    final DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(data);
    dos.flush();
}

can I be sure that calling this method either throws IOException (and that means that I'd better close the socket), or, if no exceptions are thrown, the data I send is guaranteed to be fully send? Are there any cases when I read the data on the other endpoint, the string I get is incomplete and there are no exception?


There is a big difference between sent and received. You can send data from the application successfully, however it then passes to

  • the OS on your machine
  • the network adapter
  • the switch(s) on the network
  • the network adapter on the remote machine
  • the OS on the remote machine
  • the application buffer on the remote machine
  • whatever the application does with it.

Any of these stages can fail and your sender will be none the wiser.

If you want to know the application has received and processed the data successfully, it must send you back a message saying this has happened. When you receive this, then you know it was received.


Yes, several things may happen. First of all, keep in mind write returns really quickly, so don't think much error checking (has all my data been ACKed ?) is performed.

Door number 1

You write and flush your data. TCP tries as hard as it can to deliver it. Which means it might perform retransmits and such. Of course, your send doesn't get stuck for such a long period (in some cases TCP tries for 5-10 minutes before it nukes the connections). Thus, you will never know if the other side actually got your message. You will get an error message on the next operation on the socket.

Door number 2

You write and flush your data. Because of MTU nastiness and because the string is long, it is sent in multiple packets. So your peer reads some of it and presents it to the user before getting it all.

So imagine you send: "Hello darkness my old friend, I've come to talk with you again". The other side might get "Hello darkness m". However, if it performs subsequent reads, it will get the whole data. So the far side TCP has actually received everything, it has ACKed everything but the user application has failed to read the data in order to take it out of TCPs hands.

0

精彩评论

暂无评论...
验证码 换一张
取 消