Opening a Server for Business
Problem
You need to write a socket-based server.
Solution
Create a
ServerSocket
for the given port number.
Discussion
The ServerSocket represents the “other
end” of a connection, the server that waits patiently for
clients to come along and connect to it. You construct a
ServerSocket with just the port number;[37] since it doesn’t need
to connect to another host, it doesn’t need a particular
host’s address as the client socket constructor does.
Assuming the ServerSocket constructor
doesn’t throw an exception, you’re in business. Your next
step is to await client activity, which you do by calling
accept( )
. This call blocks until a client
connects to your server; at that point, the accept( ) returns to you a Socket object (not a
ServerSocket) that is connected in both directions
to the Socket object on the client (or its
equivalent, if written in another language). Example 16-1 shows the code for a
socket-based server.
Example 16-1. Listen.java
/** * Listen -- make a ServerSocket and wait for connections. */ public class Listen { /** The TCP port for the service. */ public static final short PORT = 9999; public static void main(String[] argv) throws IOException { ServerSocket sock; Socket clientSock; try { sock = new ServerSocket(PORT); while ((clientSock = sock.accept( )) != null) { // Process it. process(clientSock); } } catch (IOException e) { System.err.println(e); } } /** This would do something with one client. */ static void process(Socket s) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access