Rabu, 14 Desember 2011

Program clientThread.java

import java.io.*;
import java.net.*;
class clientThread extends Thread{
    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;     
    clientThread t[];
    public clientThread(Socket clientSocket, clientThread[] t){
    this.clientSocket=clientSocket;
        this.t=t;
    }
    public void run()
    {
    String line;
        String name;
    try{
        is = new DataInputStream(clientSocket.getInputStream());
        os = new PrintStream(clientSocket.getOutputStream());
        os.println("Masukkan Nama Anda : .");
        name = is.readLine();
        os.println("Hello "+name+" anda telah bergabung di chat room.\nuntuk keluar dari room masukkan /quit pada baris baru");
        for(int i=0; i<=9; i++)
        if (t[i]!=null && t[i]!=this)
            t[i].os.println("*** User Baru "+name+" masuk di chat room !!! ***" );
        while (true) {
        line = is.readLine();
                if(line.startsWith("/quit")) break;
        for(int i=0; i<=9; i++)
            if (t[i]!=null)  t[i].os.println("<"+name+"> "+line);
        }            
        for(int i=0; i<=9; i++)
        if (t[i]!=null && t[i]!=this)
            t[i].os.println("*** User "+name+" telah meninggalkan room !!! ***" );
        os.println("*** Bye "+name+" ***");
        for(int i=0; i<=9; i++)
        if (t[i]==this) t[i]=null;        
        is.close();
        os.close();
        clientSocket.close();
    }
    catch(IOException e){};
    }
}