Order the Book

Class NetworkServer

java.lang.Object
  |
  +--NetworkServer
Direct Known Subclasses:
EchoServer

public class NetworkServer
extends Object

A starting point for network servers. You'll need to override handleConnection, but in many cases listen can remain unchanged. NetworkServer uses SocketUtil to simplify the creation of the PrintWriter and BufferedReader.

Taken from Core Servlets and JavaServer Pages from Prentice Hall and Sun Microsystems Press, http://www.coreservlets.com/. © 2000 Marty Hall; may be freely used or adapted.


Constructor Summary
NetworkServer(int port, int maxConnections)
          Build a server on specified port.
 
Method Summary
 int getMaxConnections()
          Gets the max connections server will handle before exiting.
 int getPort()
          Gets port on which server is listening.
protected  void handleConnection(Socket server)
          This is the method that provides the behavior to the server, since it determines what is done with the resulting socket.
 void listen()
          Monitor a port for connections.
 void setMaxConnections(int maxConnections)
          Sets max connections.
protected  void setPort(int port)
          Sets port.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

NetworkServer

public NetworkServer(int port,
                     int maxConnections)
Build a server on specified port. It will continue to accept connections, passing each to handleConnection until an explicit exit command is sent (e.g., System.exit) or the maximum number of connections is reached. Specify 0 for maxConnections if you want the server to run indefinitely.
Method Detail

listen

public void listen()
Monitor a port for connections. Each time one is established, pass resulting Socket to handleConnection.

handleConnection

protected void handleConnection(Socket server)
                         throws IOException
This is the method that provides the behavior to the server, since it determines what is done with the resulting socket. Override this method in servers you write.

This generic version simply reports the host that made the connection, shows the first line the client sent, and sends a single line in response.


getMaxConnections

public int getMaxConnections()
Gets the max connections server will handle before exiting. A value of 0 indicates that server should run until explicitly killed.

setMaxConnections

public void setMaxConnections(int maxConnections)
Sets max connections. A value of 0 indicates that server should run indefinitely (until explicitly killed).

getPort

public int getPort()
Gets port on which server is listening.

setPort

protected void setPort(int port)
Sets port. You can only do before "connect" is called. That usually happens in the constructor.

Order the Book

Order
CSAJSP @ amazon.com

Return to Top-Level Source Code Archive