|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(7) For additional information about the regular eXPression library, see the Regular EXPressions and the Java Programming Language article referenced in the Java.sun.com/developer/technicalArticles/releases/nio/#Resources">Resources. Socket ChannelsMoving on from file channels takes us to channels for reading from and writing to socket connections. These channels can be used in a blocking or non-blocking fashion. In the blocking fashion, they just replace the call to connect or accept, depending on whether you are a client or a server. In the non-blocking fashion, there is no equivalent. The new classes to deal with for basic socket reading and writing are the InetSocketAddress class in the Java.net package to specify where to connect to, and the SocketChannel class in the Java.nio.channels package to do the actual reading and writing operations. Connecting with InetSocketAddress is very similar to working with the Socket class. All you have to do is provide the host and port: String host = ...;InetSocketAddress socketAddress = newInetSocketAddress(host, 80); Once you have the InetSocketAddress, that's where life changes. Instead of reading from the socket's input stream and writing to the output stream, you need to open a SocketChannel and connect it to the InetSocketAddress: SocketChannel channel = SocketChannel.open();channel.connect(socketAddress);
|