Search code examples
javasocketsserversocket

How ServerSocket deal with multiple connection from clients at the same time?


Ok, so let´s clarify the questions...

I'm studing Sockets in Java, from my understood until now, related to this subject are:

  • To make multiple clients to connect to only one address in the server (port), then it is necessary to assign each client connection to another thread

Based on that I got confused about somethings AND could not find any acceptable answer here or at Google until now.

  1. If Socket is synchronous, what happens if 2 clients try to connect AT THE SAME TIME and how the server decides who will connect first?

  2. How the server process multiple messages from one client? I mean, does it process in order? Return ordered?

  3. Same question above BUT with multiple messages from multiple clients?

  4. If the messages are not ordered, how to achieve that? (in java)

Sorry about all those questions but for me all of them are related...

Edit: As the comment said, I misunderstood the concept of synchronization, so changed that part. Guys we ask here to LEARN not to get judged by other SO think about that before giving -1 vote ok.


Solution

  • what happens if 2 clients try to connect AT THE SAME TIME

    It is impossible for 2 clients to connect at exactly the same time: networking infrastructure guarantees it. Two requests happening at the exact same time is called a collision (wikipedia), and the network handles it in some way: it can be through detection or through avoidance.

    How the server process multiple messages from one client? I mean, does it process in order?

    Yes. The Socket class API uses the TCP/IP protocol, which includes sequence numbers in every segment, and re-orders segments so that they are processed in the order they are sent, which may be different from the order they are received.

    If you used DatagramSocket instead, that would use UDP, which does not guarantee ordering.

    Same question above BUT with multiple messages from multiple clients?

    There are no guarantees of the relative ordering of segments sent from multiple sources.