Magazine
 

Tips & Tricks

 
// new thread to update the list of user name
MyThread1 my=new
MyThread1(s1,al1,s,s2);
Thread t1=new Thread(my);
t1.start();
}
}
public static void main(String[] args){
try{
new MyServer();
}catch (IOException e){}
}
}
//class is used to update the list of user name
class MyThread1 implements Runnable{
Socket s1,s,s2;
static ArrayList al1;
DataInputStream ddin;
String sname;
MyThread1(Socket s1,ArrayList al1,Socket
s,Socket s2){
this.s1=s1;
this.al1=al1;
this.s=s;
this.s2=s2;
}
public void run(){
try{
ddin=new
DataInputStream(s1.getInputStream());
while(true){
sname=ddin.readUTF();
System.out.println(“Exit :”+sname);
//remove the logged out user name from
arraylist
MyThread2.alname.remove(sname);
MyThread2.every();
al1.remove(s1);
MyThread.al.remove(s);
MyThread2.al2.remove(s2);
if(al1.isEmpty())
System.exit(0); //all clients are logged out.
}
}catch(Exception ie){}
}
}
// class is used to maintain the list of all online
users
class MyThread2 implements Runnable{
Socket s2;
static ArrayList al2;
 

static ArrayList alname;
static DataInputStream din1;
static DataOutputStream dout1;
MyThread2(Socket s2,ArrayList al2,ArrayList
alname){
this.s2=s2;
this.al2=al2;
this.alname=alname;
}
public void run(){
try{
din1= new
DataInputStream(s2.getInputStream());
// store the user name in arraylist
alname.add(din1.readUTF());
every();
}catch(Exception oe){}
}
// send the list of user name to all clients
static void every()throws Exception{
Iterator i1=al2.iterator();
Socket st1;
while(i1.hasNext()){
st1=(Socket)i1.next();
dout1=new
DataOutputStream(st1.getOutputStream());
ObjectOutputStream obj=new
ObjectOutputStream(dout1);
//write the list of users in stream of all clients
obj.writeObject(alname);
dout1.flush();
obj.flush();
} }}
//class is used to receive the message and
//send it to all clients
class MyThread implements Runnable{
Socket s;
static ArrayList al;
DataInputStream din;
DataOutputStream dout;







Nov 2007 | Java Jazz Up | 65
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69   Download PDF