| Switchboard.java |
package SimpleChatOne;
// Fri Oct 15 18:07:43 EST 2004
//
// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain. Share and enjoy. Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.*;
// Note, most of the methods in this class are synchronized. Since
// each instance of Handler is running as its own thread, we have to
// worry about more than one of them trying to use our methods at the
// same time. We could have used a Hashtable (which is synchronized
// by default) instead of a Map. Or we could have used a Synchronized
// version of HashMap, by way of the
// Collections.synchronizedCollection() method. But we'd still have
// to synchronize when iterating through the map in the method below,
// sendToAllConnections. So instead we just synchronize each method.
// This is probably not the most efficient way to do things, but it
// allows the code to be clearer and simpler. Always remember the
// three rules of optimization;
//
// 1) Don't do it.
// 2) Don't do it yet.
// 3) Profile and measure.
public class Switchboard {
private Map map = null;
public Switchboard() {
map = new HashMap();
}
public synchronized void add(Handler handler) {
map.put(handler, handler);
}
// See the
public synchronized void remove(Handler handler) {
map.remove(handler);
}
public synchronized void sendToAllConnections(Handler from, byte[] data, int numBytes) {
// Create a version of 'data' with name of the 'from' handler
// prepended.
byte[] msg = (from.getName() + ": " + new String(data, 0, numBytes)).getBytes();
Iterator iter = map.values().iterator();
while(iter.hasNext()) {
Handler handler = (Handler)iter.next();
if(from != handler)
handler.write(msg, msg.length);
}
}
}