Java Reference
In-Depth Information
more reasons, you cannot rely on clients to close sockets, even when the protocol re‐
quires them to, which this one doesn't.
Example 9-1
puts this all together. It uses Java 7's try-with-resources to autoclose the
sockets.
Example 9-1. A daytime server
import
java.net.*
;
import
java.io.*
;
import
java.util.Date
;
public
class
DaytimeServer
{
public
final
static
int
PORT
=
13
;
public
static
void
main
(
String
[]
args
)
{
try
(
ServerSocket
server
=
new
ServerSocket
(
PORT
))
{
while
(
true
)
{
try
(
Socket
connection
=
server
.
accept
())
{
Writer
out
=
new
OutputStreamWriter
(
connection
.
getOutputStream
());
Date
now
=
new
Date
();
out
.
write
(
now
.
toString
()
+
"\r\n"
);
out
.
flush
();
connection
.
close
();
}
catch
(
IOException
ex
)
{}
}
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
The class has a single method,
main()
, which does all the work. The outer
try
block
traps any
IOException
s that may arise while the
ServerSocket
object
server
is con‐
structed on the daytime port. The inner
try
block watches for exceptions thrown while
the connections are accepted and processed. The
accept()
method is called within an
infinite loop to watch for new connections; like many servers, this program never ter‐
minates but continues listening until an exception is thrown or you stop it manually.
The command for stopping a program manually depends on your
system; under Unix, Windows, and many other systems, Ctrl-C will
do the job. If you are running the server in the background on a Unix
system, stop it by finding the server's process ID and killing it with the
kill
command (
kill
pid
)
.