Adham
Adham

Reputation: 64904

How to design a multi-client/server application?

In a socket-based application (client/server), I want to make the server perform as a proxy(manager) to handle several clients, and to get the message from one client and send it to the client, identified by an ID.

How can I know the required client running on different thread, how can I get the socket of the associate client that the id represents?

Upvotes: 2

Views: 1169

Answers (3)

Jord Sonneveld
Jord Sonneveld

Reputation: 456

Just keep an in-memory hashmap of some sort of client-id to the java.net.Socket object that represents that client's socket. You need to come up with some way of assigning client IDs, either client supplied, or server-supplied through some authorization scheme.

When a message comes in for a client ID, grab the socket from the map and send it a message. This map needs to be stored in a singleton-type object, and needs to be properly synchronized. Use a concurrent hash map. Also, socket reads and writes would need to be synchronized if you're going multi-threaded.

I have posted some example code as a github gist. It's a bit different than I explained above. I don't store sockets in the map, I store client handlers which have the socket. Also, socket reads don't need synchronization: each clients has its own thread which is the only thread reading from the socket. Socket writes do need to be synchronized though, because the thread of the sending client is writing to the socket of the receiving client.

You're probably better off using something like JBoss Netty rather than rolling your own though.

Upvotes: 3

ty812
ty812

Reputation: 3323

Save the messages to be delivered into a database, and make your threads check the database for new messages to be delivered to "their" clients on a regular basis.

If you do not want a dedicated database for the messages, build a flat file with simple ClientID->Socket mappings and use it like a "telephone book" kind of lookup system. Depending on the amount of clients you are planning to add, each thread could pre- and regularily reload such a file into it's memory for faster access...

Upvotes: 0

italiano40
italiano40

Reputation: 496

you can keep a lot of information about ID so each time it connects you get like the ip and save the thread it is running on and then you use like a hashmap to link the id to all that info then you can easily get the thread it is running on and send the information to the correct client

Upvotes: 1

Related Questions