Received Java socket message

I would like to write a socket program ...

Socket socket = new Socket("127.0.0.1",12345); DataOutputStream output = new DataOutputStream( socket.getOutputStream() ); output.writeUTF("Hello"); output.writeUTF("World"); ... ... 

"Hello", "World" ... which line arrives first? Does the connector guarantee order?

+4
source share
1 answer

The TCP protocol ensures that all messages are sent completely and in order. Thus, you can rely on the premise that the "World" will always appear after the "Hello." If for some reason the Hello packet is lost, the delivery of the World packet to another application will be delayed, and the Hello packet will be requested again.

This is automatically handled by the network stacks of the operating systems of the hosts involved - you do not need to do anything for this as an application programmer.

For more information on how TCP works, I can recommend you an article about it .

If you use a UDP socket, on the other hand, the situation is different. UDP does not guarantee consistency or reliability, so it is possible that one packet will overtake another (so that the user receives "World" before "Hello"), or even one that is lost (the user receives only "Hello" or only "World").

The standard Socket class uses TCP by default. You can override this by telling him to use UDP in the constructor, passing true as the third parameter (which is deprecated), or when you passed the custom socket implementation to the static method Socket.setSocketImplFactory , which uses UDP (which would be crazy - the purpose of this method is to implement exotic transport layer protocols that are neither UDP nor TCP).

Typically, UDP sockets are represented by the DatagramSocket class.

+6
source

All Articles