O'Reilly logo

Java in a Nutshell, 5th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

SocketChannel

Synopsis

This class is a channel for communicating over a java.net.Socket. It implements ReadableByteChannel and WriteableByteChannel as well as GatheringByteChannel and ScatteringByteChannel. It is a subclass of SelectableChannel and can be used with a Selector.

Create a new SocketChannel with one of the static open( ) methods. The no-argument version of open( ) creates a new SocketChannel but does not connect it to a remote host. The other version of open( ) opens a new channel and connects it to the specified java.net.SocketAddress. If you create an unconnected socket, you can explictly connect it with the connect( ) method. The main reason to open the channel and connect to the remote host in separate steps is if you want to do a nonblocking connect. To do this, first put the channel into nonblocking mode with the inherited configureBlocking( ) method. Then, call connect( ) : it will return immediately, without waiting for the connection to be established. Then register the channel with a Selector specifying that you are interested in SelectionKey.OP_CONNECT operations. When you are notified that your channel is ready to connect (see Selector and SelectionKey for details) simply call the nonblocking finishConnect( ) method to complete the connection. isConnected( ) returns true once a connection is established, and false otherwise. isConnectionPending( ) returns true if connect( ) has been called in blocking mode and has not yet returned, or if connect( ) has ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required