Java Reference
In-Depth Information
When a client connects,
accept()
returns a
Socket
, which is stored in the local variable
connection
, and the program continues. It calls
getOutputStream()
to get the output
stream associated with that
Socket
and then chains that output stream to a new
Out
putStreamWriter
,
out
. A new
Date
object provides the current time. The content is
sent to the client by writing its string representation on
out
with
write()
.
Connecting from Telnet, you should see something like this:
$
telnet
localhost
13
Trying
127.0
.
0.1
...
Connected
to
localhost
.
Escape
character
is
'
^]
'
.
Sat
Mar
30
16
:
15
:
10
EDT
2013
Connection
closed
by
foreign
host
If you run this program on Unix (including Linux and Mac OS X), you
need to run it as root in order to connect to port 13. If you don't want
to or can't run it as root, change the port number to something above
1024—say, 1313.
Serving Binary Data
Sending binary, nontext data is not significantly harder. You just use an
Output
Stream
that writes a
byte
array rather than a
Writer
that writes a
String
.
Example 9-2
demonstrates with an iterative time server that follows the time protocol outlined in
RFC 868. When a client connects, the server sends a 4-byte, big-endian, unsigned integer
specifying the number of seconds that have passed since 12:00 A.M., January 1, 1900,
GMT (the epoch). Once again, the current time is found by creating a new
Date
object.
However, because Java's
Date
class counts milliseconds since 12:00 A.M., January 1,
1970, GMT rather than seconds since 12:00 A.M., January 1, 1900, GMT, some con‐
version is necessary.
Example 9-2. A time server
import
java.io.*
;
import
java.net.*
;
import
java.util.Date
;
public
class
TimeServer
{
public
final
static
int
PORT
=
37
;
public
static
void
main
(
String
[]
args
)
{
// The time protocol sets the epoch at 1900,
// the Date class at 1970. This number
// converts between them.