This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'm just working with some basic socketing right now. So I made this chat client and server. Problem is you have to take turns typing messages back and forth. I am pretty new to java and I'm not too good with threads. What I want to know how to do is put the Recieving part and the Sending part in seperate threads so that it checks on both of them so that you don't have to take turns. Unless there is a better practice for something like this of course. After a few attempts I had to break down and ask other people. All I ask is a little guidance, I'm not asking anybody to write the script for me. Client:
[ July 04, 2003: Message edited by: Joel Larson ]
Joined: Mar 29, 2003
Message here was editted in to original message. [ July 04, 2003: Message edited by: Joel Larson ]
I think this is typical of socket servers staring a new thread for each new client:
My client also spins a thread to handle responses from the server.
This whole program is here. It's not a chat thing, but some of the socket client and server ideas may work for you. Oh, and it's not bug free, either! Something is not right in what it does after handling a command.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
In particular, see the last two listings, for KKMultiServer and KKMultiServerThread. I think this is typical of socket servers staring a new thread for each new client: This is the standard technique for handling multiple clients concurrently. As of JDK 1.4 it's also possible to use a Selector for improved efficciency. If you have a lot of sockets where most are not really active at any one time, then you can have a single thread listen to all of them using a Selector. And whenever something of interest happens on one of the sockets, use another thread (probably obtained from a thread pool) to service that socket. The idea is to avoid having a bunch of threads sitting around waiting for something to happen, taking up resources. Instead have a smaller number of threads, that are actually doing something. This sort of design may not be necessary for a small server (especially if it's your first one), but it's worth remembering that other options exist.