Java Reference
In-Depth Information
application must do three things: open a port, accept and establish client connections,
and then communicate with the client connections in some way. In the solution to this
recipe, the SocketServer class does all three.
Starting with the main() method, the class begins by opening a new socket on
port 1234 . This is done by creating a new instance of ServerSocket and passing a
port number to it. The port number must not conflict with any other port that is cur-
rently in use on the server. It is important to note that ports below 1024 are usually re-
served for operating system use, so choose a port number above that range. If you at-
tempt to open a port that is already in use, the ServerSocket will not successfully
be created, and the program will fail. Next, the ServerSocket object's accept()
method is called, returning a new Socket object. Calling the accept() method will
do nothing until a client attempts to connect to the server program on the port that has
been set up. The accept() method will wait idly until a connection is requested and
then it will return the new Socket object bound to the port that was set up on the
ServerSocket . This socket also contains the remote port and hostname of the client
attempting the connection, so it contains the information on two endpoints and
uniquely identifies the TCP connection.
At this point, the server program can communicate with the client program, and it
does so using the PrintWriter and BufferedReader objects. In the solution to
this recipe, the communicateWithClient() method contains all the code neces-
sary to accept messages from the client program, sends messages back to the client,
and then returns control to the main() method that closes the ServerSocket . A
new BufferedReader object can be created by generating a new In-
putStreamReader instance using the socket's input stream. Similarly, a new
PrintWriter object can be created using the socket's output stream. Notice that this
code must be wrapped in a try-catch block in case these objects are not success-
fully created.
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
Once these objects have been successfully created, the server can communicate
with the client. It uses a loop to do so, reading from the BufferedReader object
(the client input stream) and sending messages back to the client using the
PrintWriter object. In the solution to this recipe, the server closes the connection
Search WWH ::




Custom Search