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

📄 chatserver.java

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

public class ChatServer {

  /* The Chatter program    by J M Bishop  January 1997
   * ===================    Java 1.1 January 1998
   *                        updated August 2000
   *
   * Sets up a server for multiple conversations.
   *
   * Join in by typing
   * telnet x y
   * where x and y are the computer's name and port as
   * given when the Chatter starts.
   *
   * Illustrates sockets, streams on sockets,
   * threads, synchronization and the use of lists (again).
   */

  private static LinkedList clientList = new LinkedList();
  private static int id = 0;

  public static void main(String[] args) throws IOException {
    // Get the port and created a socket there.
    int port = 8190;
    if (args.length > 0)
      port = Integer.parseInt(args[0]);
    new ChatServer (port);
  }

  ChatServer (int port) throws IOException {
    ServerSocket listener = new ServerSocket(port);
    System.out.println("The Chat Server is running on port "+port);

    // Listen for clients. Start a new handler for each.
    // Add each client to the linked list.
    while (true) {
      Socket client = listener.accept();
      new ChatHandler(client).start();
      System.out.println("New client no."+id+
          " from "+ listener.getInetAddress()+
          " on client's port "+client.getPort());
      clientList.add(client);
      id++;
    }
  }

  synchronized static void broadcast(String message, String name)
      throws IOException {
    // Sends the message to every client including the sender.
    Socket s;
    PrintWriter p;
    for (ListIterator list = clientList.listIterator(); list.hasNext();) {
      s = (Socket) list.next();
      p = new PrintWriter(s.getOutputStream(), true);
      p.println(name+": "+message);
    }
  }

  synchronized static void remove(Socket s) {
  /* Using the LinkedList remove method, removes the
   * first occurrence of the given socket object
   */
    clientList.remove(s);
    id--;
  }
}

⌨️ 快捷键说明

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