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

📄 chathandler.java

📁 Java经典例程 从外国一大学计算机教授出版物下载的代码 经典
💻 JAVA
字号:
import java.io.*;
import java.net.*;

class ChatHandler extends Thread {

  /* The Chat Handler class is called from the Chat Server:
   * one thread for each client coming in to chat.
   */

  private BufferedReader in;
  private PrintWriter out;
  private Socket toClient;
  private String name;

  ChatHandler(Socket s) {
    toClient = s;
  }

  public void run() {
    try {
      /* Create i-o streams through the socket we were
       * given when the thread was instantiated
       * and welcome the new client.
       */

      in = new BufferedReader(new InputStreamReader(
        toClient.getInputStream()));
      out = new PrintWriter(toClient.getOutputStream(), true);
      out.println("*** Welcome to the Chatter ***");
      out.println("Type BYE to end");
      out.print("What is your name? ");
      out.flush();
      String name = in.readLine();
      ChatServer.broadcast(name+" has joined the discussion.",
        "Chatter");

      // Read lines and send them off for broadcasting.
      while (true) {
        String s = in.readLine().trim();

        if (s.equals("BYE")) {
          ChatServer.broadcast(name+" has left the discussion.",
          "Chatter");
          break;
        }
        ChatServer.broadcast(s, name);
      }
      ChatServer.remove(toClient);
      toClient.close();
    }
    catch (Exception e) {
    System.out.println("Chatter error: "+e);
  }
  }

}

⌨️ 快捷键说明

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