Java Reference
In-Depth Information
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
fi nally
{
try
{
System.out.println(
"\n* Closing connection… *");
link.close();
//Step 5.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to disconnect!");
System.exit(1);
}
}
}
}
Setting up the corresponding client involves four steps…
1. Establish a connection to the server.
We create a
Socket
object, supplying its constructor with the following two
arguments:
the server's IP address (of type
InetAddress
);
the appropriate port number for the service.
(The port number for server and client programs must be the same, of course!)
For simplicity's sake, we shall place client and server on the same host, which
will allow us to retrieve the IP address by calling static method
getLocalHost
of
class
InetAddress
. For example:
Socket link =
new Socket(InetAddress.getLocalHost(),1234);
2. Set up input and output streams.
These are set up in exactly the same way as the server streams were set up (by call-
ing methods
getInputStream
and
getOutputStream
of the
Socket
object that was cre-
ated in step 2).
3. Send and receive data.
The
Scanner
object at the client end will receive messages sent by the
PrintWriter
object at the server end, while the
PrintWriter
object at the client end will send mes-
sages that are received by the
Scanner
object at the server end (using methods
next-
Line
and
println
respectively).
Search WWH ::
Custom Search