mtrc
mtrc

Reputation: 1345

How are multiple clients handled in (Java-based) TCP?

I feel these might be basic topics, but I couldn't find them succinctly answered elsewhere.

When building a TCP server, my understanding is that each connecting client has to be farmed off to its own port in order to maintain sensible connectivity (e.g. to know that this message is coming from this client).

How does one set this up? I assume that you'd have a List and a dedicated 'entry point' Socket that people connected to. The connecting Socket would find a free port, reply with the port number, and set up a new Socket listening on that port. Does this sound about right?

If this is the case, it seems to me that the entry Socket would need to block while listening for incoming connections. Is this blocking read done on a separate thread?

Additional side-question: I really just need some simple message-passing for a basic Java game I want to experiment with. Things like Netty seem like a sledgehammer for this particular walnut of an application. Am I best off writing something nice and lightweight using the Java standard library?

Upvotes: 1

Views: 855

Answers (2)

Erick Robertson
Erick Robertson

Reputation: 33078

The main socket is called a "mother socket" and you block on it waiting for new connections. When a new connection happens, you use the accept() method which creates a new socket just for the new client.

You can manage these sockets by using a Selector. You configure the selector to listen to the mother socket and also any other sockets that you created. This way, you can have one thread listening for all incoming communication. If the new communication is on the mother socket, you accept the connection and generate a new socket and add it to the selector. If the new communication is on one of the other sockets, then you handle the message appropriately.

I always write my own networking code. It's a useful learning experience, but you also know exactly what these things are doing.

Upvotes: 1

artbristol
artbristol

Reputation: 32407

The client continues to use the same TCP destination port. Multiple connections are handled by the TCP stack based on the IP address and source port (randomly chosen by the client). You don't really need to concern yourself with this though. See the Oracle Java IO tutorials for how to deal with handing off connections to separate threads, they are rather good.

Upvotes: 1

Related Questions