Java Reference
In-Depth Information
dialogue is to cease and what fi nal data (if any) should be sent by the server. For this
simple example, the string “***CLOSE***” will be sent by the client when it
wishes to close down the connection. When the server receives this message, it will
confi rm the number of preceding messages received and then close its connection to
this client. The client, of course, must wait for the fi nal message from the server
before closing the connection at its own end.
Since an
IOException
may be generated by any of the socket operations, one or
more
try
blocks must be used. Rather than have one large
try
block (with no
variation in the error message produced and, consequently, no indication of precisely
what operation caused the problem), it is probably good practice to have the opening
of the port and the dialogue with the client in separate
try
blocks. It is also good
practice to place the closing of the socket in a
fi nally
clause, so that, whether an
exception occurs or not, the socket will be closed (unless, of course, the exception is
generated when actually closing the socket, but there is nothing we can do about that).
Since the
fi nally
clause will need to know about the
Socket
object, we shall have
to declare this object within a scope that covers both the
try
block handling the
dialogue and the
fi nally
block. Thus, step 2 shown above will be broken up into
separate declaration and assignment. In our example program, this will also mean
that the
Socket
object will have to be explicitly initialised to
null
(as it will not be
a global variable).
Since a server offering a public service would keep running indefi nitely, the call to
method
handleClient
in our example has been placed inside an 'infi nite' loop, thus:
do
{
handleClient();
}while (true);
In the code that follows (and in later examples), port 1234 has been chosen for
the service, but it could just as well have been any integer in the range 1024-65535.
Note that the lines of code corresponding to each of the above steps have been
clearly marked with emboldened comments.
//Server that echoes back client's messages.
//At end of dialogue, sends message indicating
//number of messages received. Uses TCP.
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoServer
{
private static ServerSocket serverSocket;
private static fi nal int PORT = 1234;
public static void main(String[] args)
Search WWH ::
Custom Search