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

📄 router.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.util.*;

public class Router extends Thread {
  static private int routerNumber;
  static private synchronized int nextRouterNum () { return routerNumber ++; }

  protected RoutingInputStream routingIn;
  protected Hashtable routes;

  public Router (MessageInput messageIn) {
    super ("Router-" + nextRouterNum ());
    routingIn = new RoutingInputStream (messageIn);
    routes = new Hashtable ();
  }

  public void register (String target, MessageOutput messageOut) {
    routes.put (target, messageOut);
  }

  public void deregister (String target) {
    routes.remove (target);
  }

  protected boolean finished;
  
  public void finish () {
    finished = true;
    interrupt ();
  }

  public void run () {
    try {
      while (!interrupted ()) {
        routingIn.receive ();
        byte[] buffer = new byte[routingIn.available ()];
        routingIn.readFully (buffer);
        String[] targets = routingIn.getTargets ();
        if (targets == null)
          broadcast (buffer);
        else
          multicast (buffer, targets);
      }
    } catch (IOException ex) {
      if (!finished)
        ex.printStackTrace ();
    }
  }

  protected void broadcast (byte[] buffer) {
    Enumeration dsts = ((Hashtable) routes.clone ()).elements ();
    while (dsts.hasMoreElements ()) {
      MessageOutput messageOut = (MessageOutput) dsts.nextElement ();
      try {
        synchronized (messageOut) {
          messageOut.write (buffer);
          messageOut.send ();
        }
      } catch (IOException ignored) {
      }
    }
  }

  protected void multicast (byte[] buffer, String[] targets) {
    for (int j = 0; j < targets.length; ++ j) {
      MessageOutput messageOut = (MessageOutput) routes.get (targets[j]);
      if (messageOut != null) {
        try {
          synchronized (messageOut) {
            messageOut.write (buffer);
            messageOut.send ();
          }
        } catch (IOException ignored) {
        }
      }
    }
  }
}

⌨️ 快捷键说明

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