Java Reference
In-Depth Information
Opening a Server Socket 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. [ 49 ] Because 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 ob-
ject (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
public
public class
Listen {
/** The TCP port for the service. */
public
class Listen
public static
static final
final short
short PORT = 9999 ;
public
public static
static void
void main ( String [] argv ) throws
throws IOException {
ServerSocket sock ;
Socket clientSock ;
try
try {
sock = new
new ServerSocket ( PORT );
while
while (( clientSock = sock . accept ()) != null
null ) {
// Process it.
process ( clientSock );
}
 
Search WWH ::




Custom Search