Java Reference
In-Depth Information
}
if
(
key
.
isReadable
())
{
SocketChannel
client
=
(
SocketChannel
)
key
.
channel
();
ByteBuffer
output
=
(
ByteBuffer
)
key
.
attachment
();
client
.
read
(
output
);
}
if
(
key
.
isWritable
())
{
SocketChannel
client
=
(
SocketChannel
)
key
.
channel
();
ByteBuffer
output
=
(
ByteBuffer
)
key
.
attachment
();
output
.
flip
();
client
.
write
(
output
);
output
.
compact
();
}
}
catch
(
IOException
ex
)
{
key
.
cancel
();
try
{
key
.
channel
().
close
();
}
catch
(
IOException
cex
)
{}
}
}
}
}
}
Closing Server Sockets
If you're finished with a server socket, you should close it, especially if the program is
going to continue to run for some time. This frees up the port for other programs that
may wish to use it. Closing a
ServerSocket
should not be confused with closing a
Socket
. Closing a
ServerSocket
frees a port on the local host, allowing another server
to bind to the port; it also breaks all currently open sockets that the
ServerSocket
has
accepted.
Server sockets are closed automatically when a program dies, so it's not absolutely nec‐
essary to close them in programs that terminate shortly after the
ServerSocket
is no
longer needed. Nonetheless, it doesn't hurt. Programmers often follow the same close-
if-not-null pattern in a
try
-
finally
block that you're already familiar with from streams
and client-side sockets:
ServerSocket
server
=
null
;
try
{
server
=
new
ServerSocket
(
port
);
// ... work with the server socket
}
finally
{
if
(
server
!=
null
)
{
try
{
server
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}