Rabu, 14 Desember 2011

Program MultiThreadChatServer.java

import java.io.*;
import java.net.*;
public class MultiThreadChatServer{
    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream
    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;
    // This chat server can accept up to 10 clients' connections
    static  clientThread t[] = new clientThread[10];
    public static void main(String args[]) {
    // The default port
    int port_number=2212;
    if (args.length < 1)
        {
        System.out.println("Usage: java  MultiThreadChatServer \n"+   "Port yang sedang digunakan="+port_number);
        } else {
        port_number=Integer.valueOf(args[0]).intValue();
        }
        try {
        serverSocket = new ServerSocket(port_number);
        }
        catch (IOException e)
        {System.out.println(e);}
    while(true){
        try {
        clientSocket = serverSocket.accept();
        for(int i=0; i<=9; i++){
            if(t[i]==null)
            {
                (t[i] = new clientThread(clientSocket,t)).start();
                break;
            }
        }
        }
        catch (IOException e) {
        System.out.println(e);}
    }
    }
}