Our server, which runs as an application, must first create an
instance of the ServerSocket
class. This is a java.net
class whose job is to monitor a given port for requests for connections
from clients.
In the code below, we create an instance ServerSocket
for a given port. We then loop over the ServerSocket
accept()
method invocation. This method does not return until a client
is detected. It then returns an instance of Socket
that provides communications with the client via a separate port.
We spin off a thread process called Worker
to service this client while the loop returns to look again for
a new client knocking at the port door.
|
import
java.net.*;
import java.io.*;
import java.util.*;
/**
* An application to create a ServerSocket
object and
* spin off a threaded process to serve each
client.
**/
public class MicroServer {
public static void main (String argv[]) throws
IOException {
int port; // port number
// Get the port number from the
command line.
try{
port = Integer.parseInt
(argv[0]);
} catch (Exception e) {
port = 2222; // Default
System.out.println
("Use default port = 2222");
}
// Create a ServerSocket object
to watch that port for clients
ServerSocket server_socket = new
ServerSocket (port);
System.out.println ("Server started");
// Loop indefinitely while waiting
for clients to connect
while (true) {
// accept () does
not return until a client requests a connection
Socket client_socket
= server_socket.accept ();
// Now that a client
has arrived, create an instance of our special
// thread subclass
to respond to it.
Worker worker = new
Worker (client_socket);
worker.start ();
System.out.println
("New client connected");
}
} // main
} // class MicroServer
|
If we don't want accept()
to wait indefinitely, we can set a timeout period with setSoTimeout(int
timeout). This will throw a SocketException
after the timout period but the ServerSocket
remains valid and accept()
can be called again.
The accept()
returns an instance of the Socket
class, which we will in turn pass to our Worker
to handle the client. We discuss the threaded Worker
class on the next page.
References & Web
Resources
Latest update: Dec. 9, 2004