O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required