Java Reference
In-Depth Information
Aftercreatinga
Socket
instance,andpossiblyinvoking
bind()
and
connect()
onthatinstance,anapplicationtypicallyinvokes
Socket
's
InputStream getIn-
putStream()
and
OutputStream getOutputStream()
methodstoobtainan
inputstreamforreadingbytesfromthesocketandanoutputstreamforwritingbytesto
thesocket.Also,theapplicationtypicallycalls
Socket
's
void close()
methodto
close the socket once it no longer needs to perform input or output operations.
Thefollowingexampledemonstrateshowtocreateasocketthat'sboundtoportnum-
ber1500onthelocalhostandthenaccessitsinputandoutputstreams—exceptionsare
ignored for brevity:
Socket socket = new Socket("localhost", 1500);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
I'vecreateda
GetTime
applicationthatdemonstratesthe
Socket
classbycreating
a socket to connect to an American National Institute of Standards & Technology
(NIST)timeservertoretrieveandoutputthecurrenttime.
Listing9-1
presentsthisap-
plication's source code.
Listing 9-1.
Getting and outputting the current time according to NIST's implementation of the
Daytime Protocol
import java.io.InputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
class GetTime
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.err.println("usage : java GetTime serv-
er");
System.err.println("example:
java
GetTime
time.nist.gov");