3/22/2009

Exercise 5-1

5-1. Investigate a simple chat client/Server system. Look at some program code and describe how it works with multiple uses.

A simple chat clent/server uses TCP/IP sockets to communicate between chat clients and chat server. In the chat client's side, users can send and view messages from server, correspondingly, in the chat server's side, it continuously listens for incoming messages from chat clients, integrates all messages and send it back to all chat clients.

I will show you some program code that is found from javaworld(2009) as follows:

a.) Classes on Chat server
In the chat server side, there are two classes, they are main class, ChatServer, is a server that accepts connections from clients and assigns them to new connection handler objects. The ChatHandler class actually does the work of listening for messages and broadcasting them to all connected clients. On thread (the main thread) handles new connections, and there is a thread (the ChatHandler class) for each client.
Every new ChatClient will connect to the ChatServer; this ChatServer will handle the connection to a new instance of ChatHandler class that will receive messages from the new client. Within the ChatHandler class, a list of the current handlers is maintained; the broadcast() method uses the list to transmit a message to all connected ChatClients. See below program code:


public class ChatServer {
public ChatServer (in port) throws IOException
{
ServerSocket server = new ServerSocker (port);
While (true) { //continuously listen for chatclient by while-loop
Socket client = server.accept();
System.out.println (“Accepted from” + clien.getInetAddress ());
ChatHandler c= new ChatHandler (client);
c.start ();}
}
public start void man (String args[]) throws IOException
{
if (arg.length !=1)
throw new RuntimeException (“Syntax: ChatServer ”);
new ChatServer (Integer.parseInt (args[0]));
}
}

For more information, please see the below figure for understanding how the class work.
1.) All ChatClient use their core function name main() to connected to ChatServer via TCP/IP socket.
2.) Each ChatClient is handled by dedicated ChatHander which is located in Chat server side.
3.) All ChatClient use the function named run() to send the message to ChatHandler.
4.) After receiving any message from ChatClient, the ChatHanlder will use the function named broadcast() in order to broadcast all received message back to all ChatClient


The figure is received from javaworld(2009)

References:

JavaWorld (2009). “Multithreaded client/sever Chat”. Received 20th March, 2009 from URL - http://www.javaworld.com/javaworld/jw-01-1997/jw-01-chat.html?page=4

沒有留言:

發佈留言