Question

I'm developing a multi-client / server application in java using TCP/IP. My server creates a new thread for each of the clientSockets (clientSocket = serverSocket.accept();). The problem seems to be in figuring out a way for all of the running threads to know about each other (i.e. for broadcasting messages to all the online users on the chat). What would be an efficient way for each of my threads to know when a new user connects to the server, as well as when an user disconnects from the server?

Was it helpful?

Solution

Me in your position would make a additional queue-thread that has a reference to the socket-threads and a message queue. All of your socket-threads can enqueue messages to the queue-thread that will then send messages to all of your socket-threads (so the socket-threads need a reference to your queue-thread/queue - Synchronization!).

As you have to expect that the ArryList? of socket-threads can change you have to use a Iterator to iterate.

To answer your question in the comments: Performance

Starting a thread per connection is quite resource intense (imagine 10.000 connections). So there are other ways to deal with it.

I would definetly go with mina:

Apache MINA is a network application framework which helps users develop high performance and high scalability network applications easily. It provides an abstract event-driven asynchronous API over various transports such as TCP/IP and UDP/IP via Java NIO.

There are plenty of tutorials on the net for MINA.

Maybe its a bit overkill but if you are interested, it's worth it.

[edit]

If its just 10-15 clients it should be fine to use a thread per connection…

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top