// Server.java -- generic network server // // author : Scott W. Matey // import java.net.*; import java.io.*; import java.util.Vector; import java.util.Enumeration; public class Server extends Object implements Runnable { Vector conns = new Vector (); ServerSocket sock; // Constructor public Server (int port) { try { sock = new ServerSocket (port); log ("Socket on port " + String.valueOf(sock.getLocalPort()) + "\n"); } catch (Exception e) { System.err.println ("Server() exception:\n" + e); System.exit(-1); } } // Listen for connections on server socket public void run () { while (true) { try { new ServerConnection (this, sock.accept ()); } catch (Exception e) { System.err.println ("Server.listen() exception:\n" + e); System.exit(-1); } } } // Internal bookkeeping methods; don't mess with these. void connect (ServerConnection c) { conns.addElement (c); notifyConnect (c); } void disconnect (ServerConnection c) { conns.removeElement (c); notifyDisconnect (c); } void log (String s) { System.out.print (s); } void broadcast (String s) { log (s); for (Enumeration e = conns.elements() ; e.hasMoreElements() ;) { ((ServerConnection)(e.nextElement())).print (s); } } // These may be overridden by subclasses. public boolean readHandshake (ServerConnection c) { return true; } public void notifyConnect (ServerConnection c) { broadcast ("[New connection from " + c.socket.getInetAddress().toString() + "]\n"); } public void notifyDisconnect (ServerConnection c) { broadcast ("[Closing connection from " + c.socket.getInetAddress().toString() + "]\n"); } public void notifyInput (String s) { } }