Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2005

Tip: Looking for answers? Try searching our database.

Chat server, threads

Thread view: 
Yaz - 15 Mar 2005 02:56 GMT
Hi,

I'm trying to write a chat program. I have no problem connecting multiple
clients to the chat server and sending/receiving messages from/to individual
clients. The part I don't understand is how to get the server to send a
message it receives from one client to all connected clients. Here's the
relevant class:

===================================
class ChatServer extends Thread {
private Socket socket;
private BufferedReader input;
private PrintWriter output;

public ChatServer(Socket s) throws IOException {
 socket = s;
 input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
 output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
   socket.getOutputStream())), true);
 start();
}

public void run() {
 try {
  while (true) {
   String str = input.readLine();
   if (str.equals("QUIT"))
    break;
   System.out.println("From client: " + str);
   output.println("From server: " + str); // Send back to client(s)
  }
  System.out.println("Quitting.");
 }
 catch(IOException e) {
  System.err.println("IO Exception");
 }
 finally {
  try {
   socket.close();
  }
  catch(IOException e) {
   System.err.println("Socket not closed!");
  }
 }
}
}
=================================

The client code simply reads whatever the server sends it, so I won't waste
space and post it.

I realize the output is being sent via a given socket to a given client. I
just don't understand how to send that input to all connected clients. Any
pointers are greatly appreciated.

Thanks.
proGex - 15 Mar 2005 08:29 GMT
>From your code, it seems to me that you are creating a new ChatServer
for every client connection? I am making a guess as the constructor
requires a socket object and also you did not post any code to show how
you are using it and also.

If you are actually do this then your design is 1 server to 1 client
only, not good for a chat server is it?  You should make your server as
a single thread able to accept multiple socket connection.  Keep track
of all sockets connected in a list (eg. in a Vector) then to broadcast
send the message to all sockets in your list
Yaz - 15 Mar 2005 10:53 GMT
Okay, thanks for clarifying. Now I get it. I ditched that approach; I
found some code which points me in the right direction. At this point,
I can successfully create a server that sends messages to all connected
clients, but not the way I want it, and not without problems. What I'm
trying to figure out now is how to get a client to receive/display the
message sent from the server as soon as the message is sent. The way it
is now, it's part of the loop that's used to send the user input to the
server. The main problem is that :
===============
while(!(input.equals("QUIT"))) {
    output.println(input);               // Send output to server
    System.out.println(in.readLine());   // Print what server returns
    input = console.readLine();          // Read user input
}
=================
I realize I have to take it out of that loop (at least, I think I do),
but I'm not sure how to handle it yet. Seems like I should create a
different thread for it, but not sure how to implement that... trying
now. Any suggestions in the meantime? Thanks again, proGex.
Yaz - 15 Mar 2005 11:04 GMT
Oops. Forgot to finish this thought:
...The main problem is that it only displays messages sent from the
server when the user submits a message. So, a whole bunch of messages
may be "backed up", and even when the user submits a message, he only
sees the next message in the queue rather than all the messages that
were sent since his last submission. Obviously not how a chat app
should work.

Somehow, I have to get the client to behave how the server behaves,
i.e., to listen for any messages sent to it and respond to them
immediately. Still looking at the thread approach...
Daniel Tahin - 15 Mar 2005 15:34 GMT
Hi Yaz!

Yes, chat app is a good example for threads...
Create a thread for sending messages to the server, and an other for
receiving messages, and create a "main" class, that will spawn these 2
threads at the program startup!
To communicate with the writer-thread, it must implement an interface!
If you want to process the message, received by the reader-thread, in
your main-class, it should implement an other interface as well!
And i think, that's all.
Any questions?

> Oops. Forgot to finish this thought:
> ...The main problem is that it only displays messages sent from the
[quoted text clipped - 7 lines]
> i.e., to listen for any messages sent to it and respond to them
> immediately. Still looking at the thread approach...
Yaz - 15 Mar 2005 16:02 GMT
Hi Daniel,

Thanks for the feedback. This thing has kept me up all night! I've got
the two threads going; one for sending, one for receiving. What's
tripping me up is how to implement the receving thread on the client.
I've tried a bunch of different ways and gotten more errors than I can
count. Can you explain specifically which interfaces need to be
implemented for which threads? Also, if I create the receiving thread
in main, should I create another class that either extends Thread or
implements Runnable, and should that class have a while loop that
handles the response from the server? That's what I'm trying to do, but
to no avail.

Thanks again!
Sameer - 15 Mar 2005 20:43 GMT
Why dont you read the IBM tutorial from Greg Travis about  writing a
multithreaded Chat Server?
This IBM tutorial can be registered from IBM DevelperWorks and can be
downloaded also.
It uses blocking approach.
If you are interested in non-blocking approach i.e. using
ServerSocketChannel and SocketChannel then do download the source code
for the book Advanced NIO again from Greg Travis, Manning Publication.
Code for Polling Chat Server is given their.
Hope this will definately help you.

-Sameer75@g


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.