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

📄 chathandler.java

📁 java网络编程方面的源码,其中有一个整合的聊天室,比较不错,建议大家下载练习,配合java网络编程技术内幕看
💻 JAVA
字号:
/* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */import java.io.*;
import java.net.*;
import java.util.*;

public class ChatHandler implements Runnable {
  protected Socket socket;
  
  public ChatHandler (Socket socket) {
    this.socket = socket;
  }

  protected DataInputStream dataIn;
  protected DataOutputStream dataOut;
  protected Thread listener;
  
  public synchronized void start () {
    if (listener == null) {
      try {
        dataIn = new DataInputStream
          (new BufferedInputStream (socket.getInputStream ()));
        dataOut = new DataOutputStream
          (new BufferedOutputStream (socket.getOutputStream ()));
        listener = new Thread (this);
        listener.start ();
      } catch (IOException ignored) {
      }
    }
  }

  public synchronized void stop () {
    if (listener != null) {
      try {
        if (listener != Thread.currentThread ())
          listener.interrupt ();
        listener = null;
        dataOut.close ();
      } catch (IOException ignored) {
      }
    }
  }

  protected static Vector handlers = new Vector ();
  
  public void run () {
    try {
      handlers.addElement (this);
      while (!Thread.interrupted ()) {
        String message = dataIn.readUTF ();
        broadcast (message);
      }
    } catch (EOFException ignored) {
    } catch (IOException ex) {
      if (listener == Thread.currentThread ())
        ex.printStackTrace ();
    } finally {
      handlers.removeElement (this);
    }
    stop ();
  }

  protected void broadcast (String message) {
    synchronized (handlers) {
      Enumeration enum = handlers.elements ();
      while (enum.hasMoreElements ()) {
        ChatHandler handler = (ChatHandler) enum.nextElement ();
        try {
          handler.dataOut.writeUTF (message);
          handler.dataOut.flush ();
        } catch (IOException ex) {
          handler.stop ();
        }
      }
    }
  }
}

⌨️ 快捷键说明

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