chathandler.java

来自「The program in the languaje java」· Java 代码 · 共 71 行

JAVA
71
字号
import java.net.*;
import java.io.*;
import java.util.*;

public class  ChatHandler  extends Thread {
  protected Socket s;
  protected DataInputStream i;
  protected DataOutputStream o;
  Vector y = new Vector();

  public ChatHandler (Socket s, Vector x) throws IOException {
    this.s = s;
    i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
    o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
    y = x;
  }

  protected static Vector handlers = new Vector ();

  
  public void run () {
    String name = s.getInetAddress ().toString ();
    String Listado="";
    try {
    	
	  for (int i=0; i < y.size() ; i++)
	  	Listado=Listado+y.get(i)+"\n";
	  
      
      
      handlers.addElement (this);
      broadcast ("->" + Listado);
      while (true) {
        String msg = i.readUTF ();
        broadcast (name + " - " + msg);
      }
    } catch (IOException ex) {
      ex.printStackTrace ();
    } finally {
      handlers.removeElement (this);
      y.remove(name);
      Listado="";
	  for (int i=0; i < y.size() ; i++)
	  	Listado=Listado+y.get(i)+"\n";
      broadcast ("<-" + Listado);
      try {
        s.close ();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }

  protected static void broadcast (String message) {
    synchronized (handlers) {
      Enumeration e = handlers.elements ();
      while (e.hasMoreElements ()) {
        ChatHandler c = (ChatHandler) e.nextElement ();
        try {
          synchronized (c.o) {
            c.o.writeUTF (message);
          }
          c.o.flush ();
        } catch (IOException ex) {
          c.stop ();
        }
      }
    }
  }
} 

⌨️ 快捷键说明

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