Rabu, 14 Desember 2011

Program MultiThreadChatClient.java

import java.io.*;
import java.net.*;
public class MultiThreadChatClient implements Runnable{
    // keterangan deklarasi
    // clientClient: the client socket
    // os:  output stream
    // is:  input stream
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;
    public static void main(String[] args) {
    // port default
    int port_number=2212;
        String host="localhost";
    if (args.length < 2)
        {
        System.out.println("Usage: java MultiThreadChatClient  \n"+ "Host yang digunakan="+host+", Nomer Port="+port_number);
        } else {
        host=args[0];
        port_number=Integer.valueOf(args[1]).intValue();
        }
    // Initialization section:
    // membuka socket dengan memberikan host dan port
    // membuka input dan output stream
    try {
            clientSocket = new Socket(host, port_number);
            inputLine = new BufferedReader(new InputStreamReader
(System.in));
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("HOST TAK TERDETEKSI "+host);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to the host "+host);
        }
        if (clientSocket != null && os != null && is != null) {
            try {
        //  membuat thread untuk membaca dari server
                new Thread(new MultiThreadChatClient()).start();
        while (!closed) {
                    os.println(inputLine.readLine());
                }
        os.close();
        is.close();
        clientSocket.close();
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }
    public void run() {
    String responseLine;
    // server tetap akan hidup selama kita belum menulis "bye""
    try{
        while ((responseLine = is.readLine()) != null) {
        System.out.println(responseLine);
        if (responseLine.indexOf("*** Bye") != -1) break;
        }
            closed=true;
    } catch (IOException e) {
        System.err.println("IOException:  " + e); } }}