Java Reference
In-Depth Information
for
(
int
i
=
0
;
i
<
4
;
i
++)
{
secondsSince1900
=
(
secondsSince1900
<<
8
)
|
raw
.
read
();
}
long
secondsSince1970
=
secondsSince1900
-
differenceBetweenEpochs
;
long
msSince1970
=
secondsSince1970
*
1000
;
Date
time
=
new
Date
(
msSince1970
);
return
time
;
}
finally
{
try
{
if
(
socket
!=
null
)
socket
.
close
();
}
catch
(
IOException
ex
)
{}
}
}
}
Here's the output of this program from a sample run:
$
java Time
It is Sun Mar 24 12:22:17 EDT 2013
The time protocol actually specifies Greenwich Mean Time, but the
toString()
method
in Java's
Date class
, implicitly invoked by
System.out.println()
, converts this into
the time zone of the local host, Eastern Daylight Time in this case.
Writing to Servers with Sockets
Writing to a server is not noticeably harder than reading from one. You simply ask the
socket for an output stream as well as an input stream. Although it's possible to send
data over the socket using the output stream at the same time you're reading data over
the input stream, most protocols are designed so that the client is either reading or
writing over a socket, not both at the same time. In the most common pattern, the client
sends a request. Then the server responds. The client may send another request, and
the server responds again. This continues until one side or the other is done, and closes
the connection.
the client opens a socket to port 2628 on the dict server and sends commands such as
“DEFINE eng-lat gold”. This tells the server to send a definition of the word
gold
using
its English-to-Latin dictionary. (Different servers have different dictionaries installed.)
After the first definition is received, the client can ask for another. When it's done it
sends the command “quit”. You can explore dict with Telnet like this:
$
telnet dict.org 2628
Trying 216.18.20.172...
Connected to dict.org.