home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap22 / MultiChatServer.java < prev    next >
Encoding:
Java Source  |  1997-04-20  |  4.9 KB  |  178 lines

  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.Vector;
  4. import java.util.Enumeration;
  5.  
  6. /**
  7.  * MultiChatServer -- A chat program between any number of clients.
  8.  *
  9.  * The server acts as the central clearing house of all messages.
  10.  * To run as a server, do not supply any command line arguments.
  11.  * MultiChat will start listening on the default port, waiting
  12.  * for a connection:
  13.  *
  14.  *   java MultiChatServer
  15.  */
  16.  
  17. public class MultiChatServer {
  18.     private int       port = 5001;    // The default port.
  19.     private boolean   listening = true;
  20.     private Vector    clients = new Vector();
  21.  
  22.     public static void main(String args[]) {
  23.        System.out.println("Hit control-c to exit the server.");
  24.        new MultiChatServer().server();
  25.     }
  26.    
  27.     // As a server, we create a server socket bound to the specified
  28.     // port, wait for a connection, and then spawn a thread to 
  29.     // read data coming in over the network via the socket.
  30.     
  31.     private void server() {
  32.         ServerSocket serverSock = null; 
  33.  
  34.         try {
  35.             InetAddress serverAddr = InetAddress.getByName(null);
  36.             
  37.             System.out.println("Waiting for first connection on " +
  38.                       serverAddr.getHostName() +
  39.                       " on port " + port);
  40.  
  41.             // Accept up to 50 connection at a time. 
  42.             // (This limit is just for the sake of performance.)
  43.             serverSock = new ServerSocket(port, 50);
  44.  
  45.         } catch (IOException e) {
  46.             System.out.println(e.getMessage() +
  47.                ": Failed to create server socket.");
  48.             return;
  49.         }
  50.  
  51.         while (listening) {
  52.  
  53.            try {
  54.                Socket socket = serverSock.accept();
  55.                System.out.println("Accepted connection from " +
  56.                    socket.getInetAddress().getHostName());
  57.                DataOutputStream remoteOut =
  58.                    new DataOutputStream(socket.getOutputStream());
  59.                clients.addElement(remoteOut);
  60.                new ServerHelper(socket, remoteOut, this).start();
  61.  
  62.            } catch (IOException e) {
  63.                System.out.println(e.getMessage() +
  64.                   ": Failed to connect to client.");
  65.            } 
  66.         }
  67.  
  68.         if (serverSock != null) {
  69.            try {
  70.                serverSock.close();
  71.            } catch (IOException x) {
  72.            }
  73.         }
  74.     }
  75.  
  76.     synchronized Vector getClients() {
  77.        return clients;
  78.     }
  79.  
  80.     synchronized void removeFromClients(DataOutputStream remoteOut) {
  81.        clients.removeElement(remoteOut);
  82.     }
  83.        
  84. }
  85.  
  86. /*
  87.  * ServerHelper handles one client. The server creates one new
  88.  * ServerHelper thread for each client that connects to it.
  89.  */
  90. class ServerHelper extends Thread {
  91.     private Socket sock;
  92.     private DataOutputStream remoteOut;
  93.     private MultiChatServer server;
  94.     private boolean listening = true;
  95.     private DataInputStream remoteIn;
  96.  
  97.     ServerHelper(Socket sock, DataOutputStream remoteOut,
  98.        MultiChatServer server) throws IOException
  99.     {
  100.         this.sock = sock;
  101.         this.remoteOut = remoteOut;
  102.         this.server = server;
  103.         remoteIn = new DataInputStream(sock.getInputStream());
  104.     }
  105.  
  106.     public synchronized void run() {
  107.         String s;
  108.  
  109.         try {
  110.             while (listening) {
  111.                 s = remoteIn.readUTF();
  112.                 broadcast(s);
  113.             }
  114.  
  115.         } catch (IOException e) {
  116.             System.out.println(e.getMessage() +
  117.                ": Connection to peer lost.");
  118.  
  119.         } finally {
  120.             try {
  121.                cleanUp();
  122.             } catch (IOException x) {
  123.             }
  124.         }
  125.     }
  126.  
  127.     // Send the message to all the sockets connected to the server.
  128.     private void broadcast(String s) {
  129.        Vector clients = server.getClients();
  130.        DataOutputStream dataOut = null;
  131.  
  132.        for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
  133.           dataOut = (DataOutputStream)(e.nextElement());
  134.  
  135.           if (!dataOut.equals(remoteOut)) {
  136.  
  137.              try {
  138.  
  139.                 dataOut.writeUTF(s);
  140.  
  141.              } catch (IOException x) {
  142.                 System.out.println(x.getMessage() +
  143.                    ": Failed to broadcast to client.");
  144.                 server.removeFromClients(dataOut);
  145.              }             
  146.           }
  147.        }
  148.     }
  149.  
  150.     private void cleanUp() throws IOException {
  151.        if (remoteOut != null) {
  152.           server.removeFromClients(remoteOut);
  153.           remoteOut.close();
  154.           remoteOut = null;
  155.        }
  156.  
  157.        if (remoteIn != null) {
  158.           remoteIn.close();
  159.           remoteIn = null;
  160.        }
  161.  
  162.        if (sock != null) {
  163.           sock.close();
  164.           sock = null;
  165.        }
  166.     }
  167.  
  168.     protected void finalize() throws Throwable {
  169.        try {
  170.           cleanUp();
  171.        } catch (IOException x) {
  172.        }
  173.  
  174.        super.finalize();
  175.     }
  176.  
  177. }
  178.