Java Reference
In-Depth Information
31.2.4 A Client/Server Example
This example presents a client program and a server program. The client sends data to a
server. The server receives the data, uses it to produce a result, and then sends the result back
to the client. The client displays the result on the console. In this example, the data sent from
the client comprise the radius of a circle, and the result produced by the server is the area of
the circle (see Figure 31.3).
compute area
Server
radius
Client
area
F IGURE 31.3
The client sends the radius to the server; the server computes the area and
sends it to the client.
The client sends the radius through a DataOutputStream on the output stream socket,
and the server receives the radius through the DataInputStream on the input stream socket,
as shown in Figure 31.4a. The server computes the area and sends it to the client through a
DataOutputStream on the output stream socket, and the client receives the area through
a DataInputStream on the input stream socket, as shown in Figure 31.4b. The server and
client programs are given in Listings 31.1 and 31.2. Figure 31.5 contains a sample run of the
server and the client.
Server
Client
Server
Client
radius
radius
area
area
DataInputStream
DataOutputStream
DataOutputStream
DataInputStream
socket.getInputStream
socket.getOutputStream
socket.getOutputStream
socket.getInputStream
socket
socket
socket
socket
Network
Network
(a)
(b)
F IGURE 31.4
(a) The client sends the radius to the server. (b) The server sends the area to the client.
F IGURE 31.5
The client sends the radius to the server. The server receives it, computes the
area, and sends the area to the client.
L ISTING 31.1
Server.java
1 import java.io.*;
2 import java.net.*;
3 import java.util.Date;
 
 
Search WWH ::




Custom Search