⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatserver.java

📁 卡耐基梅隆大学课程SSD8 quiz1答案
💻 JAVA
字号:
import java.io.*;  
import java.net.*;  
import java.util.*;  
  
public class ChatServer {  
  
  /* the counter of the connection */  
  static int counter = 1;  
  
  /* the host address */  
  static String serverAddress = "";  
  
  /* the group of the DataOutputStream for broadcasting */  
  static Vector<String> vectorAlias = new Vector<String>();  
  
  /* the group of the DataOutputStream for broadcasting */  
  static Vector<DataOutputStream> vectorStream = new Vector<DataOutputStream>();  
  
  /* error type and the information */  
  final String ERROR_ONE = "Error: Incorrect NUMBER OF TOKENS!";  
  
  final String ERROR_TWO = "Error: Incorrect TYPE LENGTH!";  
  
  final String ERROR_THREE = "Error: Incorrect HOST DESCRIPTION!";  
  
  final String ERROR_FOUR = "Error: Incorrect TYPE VALUE!";  
  
  /**  
   * Create a server socket as a chat server and waiting for connections and  
   * requests from clients.  
   *   
   * @throws Exception  
   */  
  public ChatServer(int port) throws Exception {  
  
    /* the server socket */  
    ServerSocket sk = new ServerSocket(port);  
  
    /* the host address */  
    serverAddress = InetAddress.getLocalHost().getHostAddress();  
  
    System.out.println("Welcome to running chat server! (adderss: "  
        + serverAddress + " port: " + port + ")\n");  
  
    while (true) {  
  
      Socket cs = sk.accept();  
      System.out.println("Accepting Client" + counter  
          + "'s connection from: " + serverAddress);  
  
      /* a thread for a client */  
      ServerThread st = new ServerThread(cs, counter++);  
      st.start();  
    }  
  }  

  class ServerThread extends Thread {  
  
    /* a client socket and the counter */  
    private Socket cs;  
  
    private int counter;  
  
    public ServerThread(Socket cs, int counter) {  
  
      this.counter = counter;  
      this.cs = cs;  
    }  
  
    public void run() {  
  
      String request = "";  
      String type = "";  
      String host = "";  
      String alias = "";  
      String hostip = "";  
      String hostname = "";  
      String message = "";  
  
      /* reader and writer declarations */  
      DataInputStream inFromClient = null;  
      DataOutputStream outToClient = null;  
  
      try {  
  
        /* reader and writer definations */  
        inFromClient = new DataInputStream(cs.getInputStream());  
        outToClient = new DataOutputStream(cs.getOutputStream());  
  
        /* push this writer into the broadcasting gruop */  
        vectorStream.add(outToClient);  
  
        /* read the requests and do the actions */  
        while (true) {  
  
          request = inFromClient.readUTF();  
  
          /* ERROR 1 prevention */  
          StringTokenizer token = new StringTokenizer(request, "^");  
          if (token.countTokens() >= 3) {  
            type = token.nextToken();  
            host = token.nextToken();  
            token.nextToken();  
            message = "";  
            while (token.hasMoreTokens()) {  
              message = message + token.nextToken() + " ";  
            }  
          } else {  
            displayError(ERROR_ONE, outToClient);  
            continue;  
          }  
  
          /* ERROR 2 prevention */  
          if (type.length() != 1) {  
            displayError(ERROR_TWO, outToClient);  
            continue;  
          }  
  
          /* ERROR 3 prevention */  
          if (host.contains("@")) {  
            alias = host.substring(0, host.indexOf("@"));  
            hostip = host.substring(host.indexOf("@") + 1, host  
                .length());  
          } else {  
            displayError(ERROR_THREE, outToClient);  
            continue;  
          }  
  
          hostname = InetAddress.getByName(hostip).getHostName();  
  
          /* do the actions */  
          switch (type.charAt(0)) {  
  
          case 'm': {  
            if (message != "")  
              sendMessage(host, alias, message);  
            break;  
          }  
  
          case 'j': {  
            while (vectorAlias.contains(alias)) {  
              alias = alias + " (" + counter + ")";  
            }  
            vectorAlias.add(alias);  
            joinIn(alias, hostname);  
            break;  
          }  
  
          case 'p': {  
            vectorStream.remove(outToClient);  
            vectorAlias.remove(alias);  
            partAway(alias, hostname);  
            break;  
          }  
  
          /* ERROR 4 prevention */  
          default: {  
            displayError(ERROR_FOUR, outToClient);  
            break;  
          }  
          }  
  
        }  
      } catch (Exception e) {  
      } finally {  
  
        /*  
         * Close the reader, writer and client socket.  
         *   
         */  
        System.out.println("Closing Client " + counter  
            + "\'s Connection...\n");  
  
        try {  
  
          if (inFromClient != null)  
            inFromClient.close();  
          if (outToClient != null)  
            outToClient.close();  
          if (cs != null)  
            cs.close();  
        } catch (Exception e) {  
        }  
      }  
    }  
  
    public void displayError(String error, DataOutputStream outToClient)  
        throws Exception {  
  
      System.err.println(error);  
      outToClient.writeUTF("m^Server@" + serverAddress + "^-^" + error  
          + "^");  
    }  
  
    /**  
     * Broadcst the message sent by a client.  
     *   
     * @param host  
     * @param alias  
     * @param message  
     * @throws Exception  
     */  
    public void sendMessage(String host, String alias, String message)  
        throws Exception {  
  
      String bout = "m^" + host + "^-^" + message + "^";  
      System.out.println("\t" + alias + " says: " + message);  
      broadcast(bout);  
    }  
  
    /**  
     * Broadcast a client joining in information.  
     *   
     * @param alias  
     * @param hostname  
     * @throws Exception  
     */  
    public void joinIn(String alias, String hostname) throws Exception {  
  
      String bout = "m^Server@" + serverAddress + "^-^" + alias  
          + " has joined from " + hostname + " (" + getCurrentTime()  
          + ")^";  
      System.out.println(alias + " has joined in from: " + hostname  
          + "\n");  
      broadcast(bout);  
    }  
  
    /**  
     * Broadcast a client parting out information.  
     *   
     * @param alias  
     * @param hostname  
     * @throws Exception  
     */  
    public void partAway(String alias, String hostname) throws Exception {  
  
      String bout = "m^Server@" + serverAddress + "^-^" + alias  
          + " has parted out who is at " + hostname + " ("  
          + getCurrentTime() + ")^";  
      System.out.println("\n" + alias + " has parted out who is at: "  
          + hostname);  
      broadcast(bout);  
    }  
  
    /**  
     * Output the messages to each client who has connected with the chat  
     * server. And print the information on the Console window.  
     *   
     * @param message  
     * @throws Exception  
     */  
    public void broadcast(String message) throws Exception {  
  
      DataOutputStream outToBroadcast;  
      for (Iterator it = vectorStream.iterator(); it.hasNext();) {  
        outToBroadcast = (DataOutputStream) it.next();  
        outToBroadcast.writeUTF(message);  
        outToBroadcast.flush();  
      }  
    }  
  
    /**  
     * Get the current time and return it. The time format is "H:M AM/PM".  
     *   
     * @return the current time  
     */  
    public String getCurrentTime() {  
  
      int hours = new Date().getHours();  
      int minutes = new Date().getMinutes();  
      boolean amOrPm = hours <= 12;  
  
      return amOrPm ? (hours + ":" + minutes + " AM") : (hours - 12 + ":"  
          + minutes + " PM");  
    }  
  
  }  
  
  /**  
   * create a chat server and do all jobs.  
   *   
   * @param args  
   * @throws Exception  
   */  
  public static void main(String[] args) throws Exception {  
  
    if (args.length != 1) {  
  
      System.err.println("Arguments error:\n\t"  
          + "Please input the port number!");  
      return;  
    }  
  
    try {  
      ChatServer chatServer = new ChatServer(Integer.parseInt(args[0]));  
    } catch (NumberFormatException e) {  
      System.err.println("Arguments error:\n\t"  
          + "Please input the port number!");  
    }  
  
    return;  
  }  
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -