ServerSockets
List 9.2 is part of a server application.
List 9.2 a simple server program
/**
* A program that listens to the port and provides HTML documents.
*/
Class simplewebserver {
Public static void main (string ARGs [])
{
Serversocket = NULL;
Socket clientsocket = NULL;
Int connects = 0;
Try
{
{
// Create a serverSocket
Serversocket = new serversocket (80, 5 );
While (connects <5)
{
// Wait for connection
Clientsocket = serversocket. Accept ();
// Service connection
Serviceclient (clientsocket );
Connects ++;
}
Serversocket. Close ();
}
Catch (ioexception IOE)
{
System. Out. println ("error in simplewebserver:" + IOE );
}
}
Public static void serviceclient (Socket Client)
Throws ioexception
{
Datainputstream inbound = NULL;
Dataoutputstream outbound = NULL;
Try
{
// Obtain the IO stream
Inbound = new datainputstream (client. getinputstream ());
Outbound = new dataoutputstream (client. getoutputstream ());
// Format the output (response header and few HTML documents)
Stringbuffer buffer = prepareoutput ();
String inputline;
While (inputline = inbound. Readline ())! = NULL)
{
// If the HTTP request is reached, a response is sent.
If (inputline. Equals (""))
{
Outbound. writebytes (buffer. tostring ());
Break;
}
}
}
Finally
{
// Clear
System. Out. println ("cleaning up connection:" + client );
TLN ("cleaning up connection:" + client );
Outbound. Close ();
Inbound. Close ();
Client. Close ();
Client. Close ();
}
}