router.java
来自「JAVA网络编程技术内幕一书的源代码」· Java 代码 · 共 90 行
JAVA
90 行
/* * 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 + =
减小字号Ctrl + -
显示快捷键?