aspose file tools*
The moose likes Threads and Synchronization and the fly likes Server Chat Program -- Thread Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Server Chat Program -- Thread Issue" Watch "Server Chat Program -- Thread Issue" New topic
Author

Server Chat Program -- Thread Issue

Kody Wright
Ranch Hand

Joined: Mar 06, 2011
Posts: 32
Hello guys,

I'm currently having an issue when trying to build a server that allows for different clients to connect and
send messages to eachother.

What I'm wanting the code to do:
When a new client connects to the server (accept() call on line 73 in Server.java) a thread is spawned for
that client and handles the input/output. If a new client connects, then another thread is spawned and
the process repeats.

Here's my problem:

Whenever a new client device thread is started it should get stuck in the while(true) loop
theoretically waiting for the client to send his next message. The problem arises when the same client sends a new message...instead of the
new message being handeled by the thread that is already running for that device, another new thread is started and the old one just
sits there taking up resources but not doing anything.

I know that I've messed up my logic somewhere...I'm just not sure exactly where. I appreciate any help that a more
experienced eye may offer.

Thanks for your time!


Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2434
    
  28

Do you have the client code? Is the client making a new connection everytime it sends a message? Looking at your code, it seems to me like the problem will happen when client opens a new connection for every message
Kody Wright
Ranch Hand

Joined: Mar 06, 2011
Posts: 32
Jayesh A Lalwani wrote:Do you have the client code? Is the client making a new connection everytime it sends a message? Looking at your code, it seems to me like the problem will happen when client opens a new connection for every message


You were right on, it was flawed client logic...not server. Thanks for the insightful reply!
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2434
    
  28

Now that your problem is solved, a few suggestions

Consider using a thread pool instead of starting threads for each client. Threads are heavy. It's better to keep them running. Also thread pool allows you to put an upper limit on how many clients can be processing simultaneously.

Rather than rely on ioexception to detect end of client session, use some sort of handshake. The client can say bye, and then you close connection. This will make resource usage less. Cleanly closing a socket connection is much lighter than relying on abrupt disconnects
 
Consider Paul's rocket mass heater.
 
subject: Server Chat Program -- Thread Issue