Java Reference
In-Depth Information
Closing
Just as with regular sockets, you should close a channel when you're done with it to free
up the port and any other resources it may be using:
public
void
close
()
throws
IOException
Closing an already closed channel has no effect. Attempting to write data to or read data
from a closed channel throws an exception. If you're uncertain whether a channel has
been closed, check with
isOpen()
:
public
boolean
isOpen
()
Naturally, this returns
false
if the channel is closed,
true
if it's open (
close()
and
isOpen()
are the only two methods declared in the
Channel
interface and shared by all
channel classes).
Starting in Java 7,
SocketChannel
implements
AutoCloseable
, so you can use it in try-
with-resources.
ServerSocketChannel
The
ServerSocketChannel
class has one purpose: to accept incoming connections. You
cannot read from, write to, or connect a
ServerSocketChannel
. The only operation it
supports is accepting a new incoming connection. The class itself only declares four
methods, of which
accept()
is the most important.
ServerSocketChannel
also inherits
several methods from its superclasses, mostly related to registering with a
Selector
for
notification of incoming connections. And finally, like all channels, it has a
close()
method that shuts down the server socket.
Creating server socket channels
The static factory method
ServerSocketChannel.open()
creates a new
ServerSock
etChannel
object. However, the name is a little deceptive. This method does not actually
open a new server socket. Instead, it just creates the object. Before you can use it, you
need to call the
socket()
method to get the corresponding peer
ServerSocket
. At this
point, you can configure any server options you like, such as the receive buffer size or
the socket timeout, using the various setter methods in
ServerSocket
. Then connect
this
ServerSocket
to a
SocketAddress
for the port you want to bind to. For example,
this code fragment opens a
ServerSocketChannel
on port 80:
try
{
ServerSocketChannel
server
=
ServerSocketChannel
.
open
();
ServerSocket
socket
=
serverChannel
.
socket
();
SocketAddress
address
=
new
InetSocketAddress
(
80
);
socket
.
bind
(
address
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
"Could not bind to port 80 because "
+
ex
.
getMessage
());
}