Java Reference
In-Depth Information
a specified port, methods that configure the various server socket options, and the usual
miscellaneous methods such as
toString()
.
In Java, the basic life cycle of a server program is this:
1. A new
ServerSocket
is created on a particular port using a
ServerSocket()
con‐
structor.
2. The
ServerSocket
listens for incoming connection attempts on that port using its
accept()
method.
accept()
blocks until a client attempts to make a connection,
at which point
accept()
returns a
Socket
object connecting the client and the
server.
3. Depending on the type of server, either the
Socket
's
getInputStream()
method,
getOutputStream()
method, or both are called to get input and output streams
that communicate with the client.
4. The server and the client interact according to an agreed-upon protocol until it is
time to close the connection.
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.
Let's demonstrate with one of the simpler protocols, daytime. Recall from the
Chap‐
ter 8
that a daytime server listens on port 13. When a client connects, the server sends
the time in a human-readable format and closes the connection. For example, here's a
connection to the daytime server at
time-a.nist.gov
:
$
telnet
time
-
a
.
nist
.
gov
13
Trying
129.6
.
15.28
...
Connected
to
time
-
a
.
nist
.
gov
.
Escape
character
is
'
^]
'
.
56375
13
-
03
-
24
13
:
37
:
50
50
0
0
888.8
UTC
(
NIST
)
*
Connection
closed
by
foreign
host
.
Implementing your own daytime server is easy. First, create a server socket that listens
on port 13:
ServerSocket
server
=
new
ServerSocket
(
13
);
Next, accept a connection:
Socket
connection
=
server
.
accept
();
The
accept()
call
blocks
. That is, the program stops here and waits, possibly for hours
or days, until a client connects on port 13. When a client does connect, the
accept()
method returns a
Socket
object.