0% found this document useful (0 votes)
87 views19 pages

Lec 8 Mulithreading (ClientServer)

The document discusses multithreaded network programming and provides examples of client-server applications implemented using sockets in Java. It describes a three way handshake protocol between a client and server where they exchange initial greeting messages. It then provides code examples of echo client-server applications using different I/O streams like BufferedReader/Writer, PrintWriter/InputStream, and ObjectInput/OutputStream. Finally, it mentions a file server example using BufferedReader/Writer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views19 pages

Lec 8 Mulithreading (ClientServer)

The document discusses multithreaded network programming and provides examples of client-server applications implemented using sockets in Java. It describes a three way handshake protocol between a client and server where they exchange initial greeting messages. It then provides code examples of echo client-server applications using different I/O streams like BufferedReader/Writer, PrintWriter/InputStream, and ObjectInput/OutputStream. Finally, it mentions a file server example using BufferedReader/Writer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Multithreading in Network Programming

- Servers should be multithreaded in order to handle concurrent access of clients


- Performance is a major issue
Example : Code Client Server Architecture to implement a Phenomenon called “Three Way
Hand Shake” using Socket programming.
The Steps Of the Program is As follows:
1. Server receives a connection with a Initial String “Hello Server”
2. The Server requests back the String “Hello Client”.
3. Then the Client sends “Want Connection”.
4. Server requests, “I am Ready”.

ServerTest.java
import java.io.*;
import java.net.*;
class MyServer {
MyServer () throws Exception{
ss= new ServerSocket(2000);//Registration
System.out.println("Server Ready...waiting for incomming requests...");
int count=1;
while (true){
s=ss.accept();//listen and accept
System.out.print("client # " + count);
System.out.println(" from Ip " + s.getInetAddress());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pr=new PrintWriter(s.getOutputStream());
ServerThread thread=new ServerThread(br,pr);
thread.start();
count++;
}
}
ServerSocket ss;
Socket s;
BufferedReader br;
PrintWriter pr;
}
class ServerThread extends Thread{
ServerThread(BufferedReader br,PrintWriter pr){
try{this.br=br;
this.pr=pr;
}catch (Exception e ) {}
}
public void run() {
String msg="";
try{
do{ msg=br.readLine();
System.out.println(msg);
if (msg.equals("Hello Server"))
pr.println("Hello Client");
else if (msg.equals("Want Connection"))
pr.println("I am Ready");
pr.flush();
Thread.sleep(9000L);
}while (!msg.equals("Want Connection"));
}catch (Exception e ) {}
}
Socket s;
BufferedReader br;
PrintWriter pr;
}
class ServerTest{
public static void main(String o[]) throws Exception{
new MyServer();
}
}

ClientTest.java
import java.io.*;
import java.net.*;
class MyClient {
MyClient() throws Exception{
s= new Socket("localhost",2000);//dialup
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pr=new PrintWriter(s.getOutputStream());
ClientThread thread=new ClientThread(br,pr);
thread.start();
}
Socket s;
InputStream in;
BufferedReader br;
PrintWriter pr;
}
class ClientThread extends Thread{
ClientThread(BufferedReader br,PrintWriter pr){
try{this.br=br;
this.pr=pr;
}catch (Exception e ) {}
}
public void run() {
String msg="";
try{pr.println("Hello Server");
pr.flush();
do{ msg=br.readLine();
System.out.println(msg);
if (msg.equals("Hello Client"))
pr.println("Want Connection");
pr.flush();
Thread.sleep(9000L);
}while (!msg.equals("I am Ready"));
}catch (Exception e ) {}
}
Socket s;
BufferedReader br;
PrintWriter pr;
}
class ClientTest {
public static void main(String o[]) throws Exception{
new MyClient();
}
}
Echo Client Server

Buffered Reader and Writers


import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
class Server {
public static void main(String args[]) throws public class Client {
Exception{ public static void main(String args[]){
char a;
ServerSocket sersoc=null;
Socket soc;
Socket client_soc; BufferedReader br=null;
BufferedReader br=null; BufferedWriter bw=null;
sersoc=new ServerSocket(2000); String data="From The Client";
System.out.println("Server Ready"); try{
while(true){ soc=new Socket("localhost",2000);
client_soc=sersoc.accept(); br=new BufferedReader(
br=new BufferedReader( new InputStreamReader(soc.getInputStream()));
new bw=new BufferedWriter(
InputStreamReader(client_soc.getInputStream())); new OutputStreamWriter(soc.getOutputStream()));
ServerThread ob=new ServerThread(br); for(int r=0;r<data.length();r++){
Thread th=new Thread(ob); a=data.charAt(r);//get one chracter
bw.write(a);// write chracter
th.start();
bw.flush();
} }
} bw.close();
}//end main classs soc.close();
class ServerThread implements Runnable{ }catch(Exception e){e.printStackTrace();}
BufferedReader br=null;
public ServerThread(BufferedReader br) }// end main
{this.br=br; } }// end class
public void run(){
try{
String st="";
while((st=br.readLine())!=null)
System.out.println(st);
br.close();
}catch(Exception e){e.printStackTrace();}
}
}// end class
Echo Client Server

Print Writer and Input Stream


import java.net.*;
import java.io.*; import java.net.*;
class server { import java.io.*;
public static void main(String args[]){
ServerSocket sersoc=null; public class client {
Socket client_soc;
InputStream in=null; public static void main(String args[]){
try{
sersoc=new ServerSocket(2000); char a;
System.out.println("Server Ready"); Socket soc;
while(true){ PrintWriter pw=null;
client_soc=sersoc.accept(); String data="From The Client";
in=client_soc.getInputStream(); try{
server_thread ob=new server_thread(in); soc=new Socket("localhost",2000);
Thread th=new Thread(ob); pw=new PrintWriter(soc.getOutputStream());
th.start();
} for(int r=0;r<data.length();r++){
}catch(Exception e){System.out.println(e);} a=data.charAt(r);//get one chracter
}// end main pw.write((int)a);// write chracter
}//end main classs pw.flush();
}
class server_thread implements Runnable{ pw.close();
InputStream in=null; soc.close();
public server_thread( InputStream in){ }catch(Exception e){e.printStackTrace();}
this.in=in; }// end main
} }// end class
public void run(){
try{
String echo_string="";
int c=0;
while(c!=-1){
c=in.read();
if(c!=-1)
echo_string=echo_string + (char)c;
}

System.out.println(echo_string);

in.close();
}catch(Exception e){e.printStackTrace();}
}
}// end class
Echo Client Server

Object Input output Stream

import java.net.*;
import java.net.*; import java.io.*;
import java.io.*;
class server { public class client {
public static void main(String args[]){
ServerSocket sersoc=null; public static void main(String args[]){
Socket client_soc;
ObjectInputStream oin=null; char a;
try{ Socket soc;
sersoc=new ServerSocket(2000); ObjectOutputStream out=null;
System.out.println("Server Ready"); String data="From The Client";
try{
while(true){ soc=new Socket("localhost",2000);
client_soc=sersoc.accept(); out=new
oin=new ObjectOutputStream(soc.getOutputStream());
ObjectInputStream(client_soc.getInputStream()); out.writeObject(new String(data));
server_thread ob=new server_thread(oin); out.close();
Thread th=new Thread(ob); soc.close();
th.start(); }catch(Exception e){e.printStackTrace();}
} }// end main
}catch(Exception e){System.out.println(e);} }// end class
}// end main
}//end main classs
class server_thread implements Runnable{
ObjectInputStream oin=null;
public server_thread(ObjectInputStream oin){
this.oin=oin;
}
public void run(){

try{

String echo_string="";
echo_string=(String)oin.readObject();
System.out.println(echo_string);
oin.close();
}catch(Exception e){e.printStackTrace();}
}
}// end class
File Server

Buffered Reader and Writers

import java.net.*; import java.net.*;


import java.io.*; import java.io.*;

class server { public class client {


public static void main(String args[]){
ServerSocket sersoc=null; public static void main(String args[]){
Socket client_soc;
BufferedWriter bw=null;
ObjectInputStream oin=null; Socket soc;
try{ BufferedReader br=null;
sersoc=new ServerSocket(2000); ObjectOutputStream out=null;
}catch(Exception w){w.printStackTrace();} String file="c:\\temp\\problema.java";
try{ try{
while(true){ soc=new Socket("localhost",2000);
System.out.println("Server Ready"); br=new BufferedReader(new
client_soc=sersoc.accept(); InputStreamReader(soc.getInputStream()));
System.out.println("Server REcived a connection"); out=new
bw=new BufferedWriter(new ObjectOutputStream(soc.getOutputStream());
OutputStreamWriter(client_soc.getOutputStream())); out.writeObject(new String(file));// writing the
oin=new file name
ObjectInputStream(client_soc.getInputStream()); int i=0;
server_thread ob=new server_thread(bw,oin); while(i!=-1){
Thread th=new Thread(ob); i=br.read();// reading
th.start(); if(i!=-1)
}// end while System.out.print((char)i);
}catch(Exception e){System.out.println(e);} }// end while
}}//end main classs br.close();
class server_thread implements Runnable{ out.close();
BufferedWriter bw=null; soc.close();
ObjectInputStream oin=null; }catch(Exception e){e.printStackTrace();}
FileInputStream fin=null; }// end main
}// end class
public server_thread(BufferedWriter
bw,ObjectInputStream oin){ int i=0;
this.bw=bw; do{
this.oin=oin;} i=fin.read();
public void run(){ if(i!=-1)
try{ String file_name=(String)oin.readObject(); bw.write(i);
String file=""; }while(i!=-1);
fin=new FileInputStream(file_name); bw.close();
int i=0; fin.close();
}catch(Exception e){System.out.println(e);}
}
}// end class
File Server
Print Writer and Input Stream
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;

class server { public class client {


public static void main(String args[]){
ServerSocket sersoc=null; public static void main(String args[]){
Socket client_soc;
ObjectInputStream oin=null;
PrintWriter pw=null; Socket soc;
InputStream in=null;
try{ ObjectOutputStream out=null;
sersoc=new ServerSocket(2000); String file="c:\\temp\\problema.java";
}catch(Exception w){w.printStackTrace();} try{
soc=new Socket("localhost",2000);
try{ in=soc.getInputStream();
out=new
while(true){ ObjectOutputStream(soc.getOutputStream());
System.out.println("Server Ready"); out.writeObject(new String(file));// writing the
client_soc=sersoc.accept(); file name
System.out.println("Server REcived a int i=0;
connection"); while(i!=-1){
pw=new i=in.read();// reading
PrintWriter(client_soc.getOutputStream()); if(i!=-1)
oin=new System.out.print((char)i);
ObjectInputStream(client_soc.getInputStream()); }// end while
server_thread ob=new server_thread(pw,oin); in.close();
Thread th=new Thread(ob); out.close();
th.start(); soc.close();
}// end while }catch(Exception e){e.printStackTrace();}
}catch(Exception e){System.out.println(e);} }// end main
}// end main }// end class
}//end main classs
public void run(){
class server_thread implements Runnable{ try{ String file_name=(String)oin.readObject();
fin=new FileInputStream(file_name);
PrintWriter pw=null; int i=0;
ObjectInputStream oin=null; do{
FileInputStream fin=null; i=fin.read();
if(i!=-1)
public server_thread( PrintWriter pw.write(i);
pw,ObjectInputStream oin){ }while(i!=-1);
this.pw=pw; pw.close();
this.oin=oin; fin.close();
} }catch(Exception e){System.out.println(e);}
}
}// end class
File Server
Object Input output Stream
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;

class server { public class client {


public static void main(String args[]){
ServerSocket sersoc=null; public static void main(String args[]){
Socket client_soc;
ObjectInputStream oin=null;
ObjectOutputStream oout=null; Socket soc;
try{ ObjectInputStream oin=null;
sersoc=new ServerSocket(2000); ObjectOutputStream out=null;
}catch(Exception w){w.printStackTrace();} String file="c:\\temp\\problema.java";
try{
try{ soc=new Socket("localhost",2000);
oin=new
while(true){ ObjectInputStream(soc.getInputStream());
System.out.println("Server Ready"); out=new
client_soc=sersoc.accept(); ObjectOutputStream(soc.getOutputStream());
System.out.println("Server REcived a out.writeObject(new String(file));// writing the
connection"); file name
oout=new String data=(String)oin.readObject();
ObjectOutputStream(client_soc.getOutputStream()); System.out.println(data);
oin=new oin.close();
ObjectInputStream(client_soc.getInputStream()); out.close();
server_thread ob=new server_thread(oout,oin); soc.close();
Thread th=new Thread(ob); }catch(Exception e){e.printStackTrace();}
th.start(); }// end main
}// end while }// end class
}catch(Exception e){System.out.println(e);}

}// end main


public void run(){
}//end main classs
try{
String file_name=(String)oin.readObject();
class server_thread implements Runnable{
String file="";
ObjectOutputStream oout=null;
fin=new FileInputStream(file_name);
ObjectInputStream oin=null;
int i=0;
FileInputStream fin=null;
do{
i=fin.read();
public server_thread(ObjectOutputStream
if(i!=-1)
oout,ObjectInputStream oin){
file=file+(char)i;
this.oout=oout;
}while(i!=-1);
this.oin=oin;
oout.writeObject(new String(file));
}
oout.close();
fin.close();
}catch(Exception e){System.out.println(e);}}
}// end class
Authorization server
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import java.util.*; public class client {
class server { public static void main(String args[]){
public static void main(String args[]){ Socket soc=null;
ServerSocket sersoc=null; ObjectOutputStream out;
Socket soc; ObjectInputStream in;
try{ try{
ObjectOutputStream out; String username="ali";
ObjectInputStream in; String password="ali";
sersoc=new ServerSocket(2000); soc=new Socket("localhost",2000);
System.out.println("Server Ready"); out=new
while(true){ ObjectOutputStream(soc.getOutputStream());
soc=sersoc.accept(); in=new
System.out.println("Recived"); ObjectInputStream(soc.getInputStream());
out=new out.writeObject(new String(username));
ObjectOutputStream(soc.getOutputStream()); out.writeObject(new String(password));
in=new ObjectInputStream(soc.getInputStream()); String ans=(String)in.readObject();
server_thread ob=new server_thread(out,in); if(ans.equalsIgnoreCase("error"))
Thread th=new Thread(ob); System.out.println(" Acces Denied");
th.start(); else
}// end while System.out.println(ans);
}catch(Exception e){ out.close(); in.close(); soc.close();
System.out.println(e); }catch(Exception e){System.out.println(e);}
}}// end main }}// end class
}// edn cclass
class server_thread implements Runnable{
ObjectOutputStream out; String login=(String)in.readObject();
ObjectInputStream in; String pass=(String)in.readObject();
int check=0; String log=login+":"+pass;
String for(int a=0;a<3;a++){
name[]={"ali:ali","umar:umar","mubeen:mubeen"}; if (name[a].equals(log)){
Hashtable marks=new Hashtable(); check=1;
break;
public server_thread(ObjectOutputStream } }
out,ObjectInputStream in){ if(check==1){
marks.put(new String("ali"),new String("20")); String m=(String)marks.get(new String(login));
marks.put(new String("umar"),new String("50")); out.writeObject(new String("The Marks are ==
marks.put(new String("hassan"),new String("70")); "+m)); }
this.out=out; else{out.writeObject(new String("error"));}
this.in=in; out.close();
} in.close();
public void run(){ }catch(Exception e){
try{ MutiThreaded Chat Server (A Case Study)
System.out.println(e);
System.out.println("in run"); }}}// end class
We will discuss this case study into four Steps

Step1 - Software demonstration

Step 2- Define Requirements


1- Server registers himself on some ip and port and then waits for client request

2- Client dials up server using ip and port.

3- Client will send his nick before sending and receiving messages.
Client nick should be unique.

4- Sever will get clients nick and check it into its local collection (i.e. HashTable)

5- If client’s nick is not already found in collection then access will be granted to client and
server will inform all clients resides in collection (already logged) about this event.
Actually nicks are socket stored in server collection. Otherwise it will deny connection with
message "DENY" to client and "Connection denied" at server side;

6- Client will send some message to server (i.e. from and to message) server will tokenize the
to, from and msg from clients string. Server will send message to "To"’s Socket.

7-On client side there is a thread which will continuously get the input from network and
displays that input on client’s console
8- Client can stop communication by typing QUIT

Step 3- Software design


1- We have two classes at client side
a) Client class
(dialup, streams open, send message)
b) ClientThread ( receive message)

2- We have two classes at Server Side


a) Server Class (Registration, streams open, hastable, access, Inform all)
b) ServerThread ( Send , rec)

Step 4- Code Discussion


/** MessengerServer.java
* Title: Multithreaded Chat Server
* Description: It is a console based multithreaded chat server that allows users to chat with
other users connected to the server.
* Copyright: : Prof. Sfarooq
*/
import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
/***********************************************************************
Messenger Server
***********************************************************************/
public class MessengerServer{
private ServerSocket server = null;
private Socket client = null;
private final int SERVER_PORT = 4000;
public Hashtable references = null;
private BufferedReader reader = null;
private PrintWriter writer = null;
/**
* Constructor that starts the server and waits for clients to connect
* on connection checks UID and if valid starts a new thread
*/

public MessengerServer(){
references = new Hashtable();
try{
server = new ServerSocket(SERVER_PORT);
System.out.println("Messenger Server Ready");
while (true){
client = server.accept();
reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(),true);
String UID = reader.readLine();

System.out.println("==========================================");
System.out.println("User requests connection with UID : " + UID);
System.out.println("Time : " + new java.util.Date());
System.out.print("Server Response : ");
/* Here UID is client nick. Server Check whether it is already in hashtable
if (assignUID(UID)){
writer.println("ACCEPT");
System.out.println("Connection granted");
references.put(UID,client);
informAll();
new MessengerServerThread(client,references,UID).start();
}else{ writer.println("DENY");
System.out.println("Connection denied");
}
}//end of while
}catch(Exception e){
System.out.println("ERROR[1] occurred : " + e.getMessage());
}
}
/**
* Returns true if the UID is not already in the hashtable i.e. assigned to
* anyone else
*/
private boolean assignUID(String UID){
if(references.containsKey(UID))
return false;
else
return true;
}
/**
* Return the current online members list
*/
private String getOnlineInfo(){
Enumeration users = references.keys();
String usersList = "";
while(users.hasMoreElements()){
usersList = usersList + " " + users.nextElement();
}
return usersList;
}
/**
* Informs all the connected clients about the latest online list
*/
private void informAll() throws Exception{
Enumeration clients = references.elements();
while(clients.hasMoreElements()){
Socket recipient = (Socket)clients.nextElement();
String msg = "Online" + " " + getOnlineInfo();
new PrintWriter(recipient.getOutputStream(),true).println(msg);
}}
/**
* The main method of the Server
*/
public static void main(String args[]){
new MessengerServer();
}
}

/***********************************************************************
Messenger Server Thread
***********************************************************************/
class MessengerServerThread extends Thread
{
private Socket client = null;
private BufferedReader reader = null;
private PrintWriter writer = null;
private Hashtable references = null;
private String UID = null;
/**
* Constructor that takes socket, hashtable and UID ans paramaters
*/
public MessengerServerThread(Socket socket,Hashtable references,String UID){
this.UID = UID;
this.references = references;
try{ client = socket;
reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(),true);
}catch(Exception e){
System.out.println("ERROR[2] occurred : " + e.getMessage());
}
}
/**
* Run method of Thread class that continously read all the messages parses
* them on the basis that each message has '<from> <to> <msg>' gets the appropriate
* socket from the references and sends te message to the recipient in the form
* '<from> <message>'.
*/
public void run(){
try{ System.out.println("Thread Started");
String msg = "";
while (!(msg = reader.readLine()).equals("QUIT")){
java.util.StringTokenizer tokenizer =
new java.util.StringTokenizer(msg);
String from = tokenizer.nextToken();
String to = tokenizer.nextToken();
Socket recipient = (Socket)references.get(to);
String str = "";
while(tokenizer.hasMoreElements())
str = str + " " + tokenizer.nextToken();
msg = from + " " + str;
new PrintWriter(recipient.getOutputStream(),true).println(msg);
}
endSession();
}catch(Exception e){
System.out.println("ERROR[3] occurred : " + e.getMessage());
}
}
/**
* Removes the UID from references
*/
private void endSession(){
try{ System.out.println("Thread Stopped : " + UID);
references.remove(UID);
reader.close();
writer.close();
}catch(Exception e){
System.out.println("ERROR[4] occurred : " + e.getMessage());}
}
}
/** MessengerClient.java
* Title: Multithreaded Chat Client
* Description: It is a DOS based multithreaded chat server that allows users to chat with other
users connected to the server.
* Copyright: Prof. Sfarooq
*
*/
import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
/*************************************************************************/
// Messenger Client
/************************************************************************/
/*
The communication follows a protocol
- Client connects to the server
- Client sends UID
- Server replies ACCEPT or DENY
- If ACCEPT then a thread starts that reads the input stream, mean time you
can send any message to anyone online by typing their nick as specified
in the 'Latest Online List' and then the message:
Name Hello
- Client can stop communication by typing QUIT
*/
public class MessengerClient{
//Current users sockets, reader, writer
private Socket socket = null;
private BufferedReader reader = null;
private static PrintWriter writer = null;
//The port where the server is running
private final int SERVER_PORT = 4000;
//The current users id
private String UID = "";
/**
* Constructor that connects to the server and starts communication by first
* sending a UID, if accepted then proceeds with a loop unless QUIT is entered
*/
public MessengerClient(){
try{//Connect to server
socket = new Socket("localhost",SERVER_PORT);
reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(),true);
//Communication starts by first entering nick
System.out.print("Enter Nick : ");
String input = getInput();
//If nick is valid and not assigned then connection establishes
if(assignUID(input)){
//Communication with others is done by first typing their name then
//a space followed by the message.
System.out.println("Usage : <Recipient's Nick> <Message>");
UID = input;
//The thread that continously reads the input stream
startThread();
System.out.print("You say > ");
//Connection reamins established unitll QUIT is typed
while(!(input=getInput()).equals("QUIT")){
sendMessage(input);
System.out.print("You say > ");
}
//Session is ended
endSession();
}else
System.out.println("Invalid Username");
}catch(Exception e){
System.out.println("ERROR[1] occurred : " + e.getMessage());}
}
/**
* Assigns a UID by sending it to the server if valid then returns true
*/
private boolean assignUID(String UID){
try{ writer.println(UID);
String result = reader.readLine();
if (result.equals("ACCEPT"))
return true;
else if (result.equals("DENY"))
return false;
else
System.exit(0);
}catch(Exception e){
System.out.println("ERROR[2] occurred : " + e.getMessage()); }
return false;
}
/**
* Starts a thread that will read the input stream
*/
private void startThread(){
new MessengerClientThread(reader).start();
}
/**
* Ends the session with the server
*/
private void endSession(){
try{writer.println("QUIT");
}catch(Exception e){
System.out.println("ERROR[4] occurred : " + e.getMessage());}
}
/**
* Gets the input from the keyboard
*/
private String getInput(){
String input = "";
try { BufferedReader reader = new
BufferedReader(new InputStreamReader(System.in));
input = reader.readLine();
} catch(Exception e) {
System.out.println("ERROR[5] occurred : " + e.getMessage()); }
return input;
}
/**
* Sends a message to the server in the format <from> <to> <message>
*/
private void sendMessage(String msg){
try{writer.println(UID + " " + msg);
}catch(Exception e){
System.out.println("ERROR[6] occurred : " + e.getMessage());}
}
/**
* Execution begins from here
*/
public static void main(String args[]){
new MessengerClient();
}
}
/***************************************************************************/
// Messenger Client Thread
/**************************************************************************/

class MessengerClientThread extends Thread{


private BufferedReader reader = null;
/**
* Constructor that takes reader as input
*/
public MessengerClientThread(BufferedReader reader){
try{this.reader = reader;
}catch(Exception e) {
System.out.println("ERROR[7] occurred : " + e.getMessage());
}
}
/**
* Thread run method that continually read from input stream
*/
public void run(){
try{ String msg = "";
String str = "";
//Reads the input stream untill QUIT is entered
while (!(msg = reader.readLine()).equals("QUIT")){
java.util.StringTokenizer tokenizer =
new java.util.StringTokenizer(msg," ");
String from = tokenizer.nextToken();
while (tokenizer.hasMoreTokens()){
str = str + " " + tokenizer.nextToken();
}
if(from.equals("Online")){
System.out.println("\n" + "Latest Online List : " + str);
System.out.print("You say > ");
}else{
System.out.println("\n" + from + " says > " + str);
System.out.print("You say > ");
}
str = "";
}//end while
}catch(Exception e){
System.out.println("Connection with server terminated");
}
}
}

You might also like