Java Reference
In-Depth Information
} else
{
int port;
try
{
port = Integer.parseInt(args[0]);
SimpleWebServer server = new SimpleWebServer(port);
server.run();
} catch (NumberFormatException e)
{
System.out.println("Invalid port number");
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Java supports two primary types of sockets: server sockets and client sockets. Server
sockets are implemented using the ServerSocket class. Client sockets are implement-
ed using the Socket class. This program begins by creating a server socket. This is done
with the following line of code in the WebServer constructor:
serverSocket = new ServerSocket(port);
Once the server connection has been opened, the program must wait for connections.
This is done using the accept function of the ServerSocket object. This is done in
the run method. The run method begins by entering an endless loop, as seen here:
for (;;)
{
This command causes the web server to wait endlessly for connections. The server does
not include a mechanism for shutting itself down. To shut down the server simply, press
ctrl-c or close the web server's window.
Next, the accept function is called to accept a connection. If no connection is avail-
able, then the accept function blocks (or waits), until a connection is available. Because
of this, the accept call is often put inside of a thread. This would allow the rest of the pro-
gram to continue executing while the thread waits for a connection. However, for this simple
example, everything will be done in a single thread.
try
{
Socket clientSocket = serverSocket.accept();
Search WWH ::




Custom Search