Java Reference
In-Depth Information
Display 19.4 Client/Server Network Communication through Sockets
1. The server listens and waits for a connection on port 7654.
Server Computer
port 0
port 1
...
port 7654
...
port 65535
Server
program
2. The client connects to the server on port 7654. It uses a local port that is assigned
automatically, in this case, port 20314.
Server Computer
Client Computer
port 0
port 1
...
port 7654
...
port 65535
port 0
port 1
...
port 20314
...
port 65535
Network
Client
program
Server
program
The client program can now
communicate over a socket bound
locally to port 20314 and remotely
to the server's address at port 7654.
The server program can now
communicate over a socket bound
locally to port 7654 and remotely
to the client's address at port 20314.
the java.net package, while the BufferedReader and DataOutputStream classes are
in the java.io package. Once the streams are created, the server expects the client to send
a name. The server waits for the name with a call to readLine( ) on the BufferedReader
object and then sends back the name concatenated with the current date and time.
Finally, the server closes the streams and sockets.
Display 19.6 shows how to create a client that connects to our date and time server. First,
we create a socket with the name of the computer running the server along with the corre-
sponding port of 7654. If the server program and client program are running on the same
computer then you can use localhost as the name of the machine. Otherwise, the host-
name should be set to the name of the computer (e.g., my.server.com). After a connection is
made, the client creates stream objects, sends its name, waits for a reply, and prints the reply.
Note that the socket and stream objects throw checked exceptions. This means that
their exceptions must be caught or declared in a throws block.
localhost
 
Search WWH ::




Custom Search