275
Proprietary Approach
When the socket is created, the two parameters passed represent the IP address and the
virtual socket the client attempts to connect to.
The IP address 127.0.0.1 is a loop-back, meaning that the client will attempt to con-
nect to a server that is local. In short, the client and server are running on the same ma-
chine.The only obvious condition is that server must be launched first.
Using this loop-back IP address is very useful when testing applications. Instead of re-
quiring a connection to a network, the underlying logic of an application can be tested
locally—which makes the initial testing much simpler. Later, more general testing can be
performed with a real IP address.
Besides the IP address, the virtual port must be specified in the parameter list. In this
case an arbitrary value of
11111 is chosen.The only condition with this value is that the
server that the client attempts to connect to must be listening at this port.
Once the client does establish valid communication with the server, and the object is
sent and retrieved, the client application simply terminates—placing a loop in the code to
make the client perform again.
The only other issue of note in this code is the method at the end of the class that
performs the task of retrieving a line from the keyboard.This is the user input, akin to
typing in a text message on your cell phone.
Server Code
On the other side of the wire, the server code performs the following tasks:
n
Create an object reference
n
Listen to the virtual port 11111
n
Wait for a client to connect
n
Create the Input/Output streams
n
Read the TextMessage object
n
Print the message
The code for the server is listed here:
import java.io.*;
import java.net.*;
/*
* The Server for TextMessage.
*/
public class Server {
public static void main(String[] arg) {
// create a reference for an object to come from the client.
TextMessage myTextMessage = null;