Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 5. NIO > Stream (TCP) Channels in Detail

5.5. Stream (TCP) Channels in Detail

Stream channels come in two varieties: SocketChannel and ServerSocketChannel. Like its Socket counterpart, a SocketChannel is a communication channel for connected endpoints.

SocketChannel: Creating, connecting, and closing

static SocketChannel open(SocketAddress remote)
static SocketChannel open()
boolean connect(SocketAddress remote)
boolean isConnected()
void close()
boolean isOpen()
Socket socket()

A SocketChannel is created by calling the open() factory method. The first form of open() takes a SocketAddress (see Chapter 2) and returns a SocketChannel connected to the specified server; note that this method may block for an indefinite period. The parameterless form of open() creates an unconnected SocketChannel, which may be connected to an endpoint with the connect() method. When you are finished with a SocketChannel, call the close() method. One important point is that each instance of SocketChannel “wraps” a basic Java Socket, which you may access using the socket() method. This will allow you to call basic Socket methods to bind, set socket options, etc. See TCPEchoClientNonblocking.java (pages 113–114) for an example of SocketChannel creation, connection, and closing.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial