|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(11) Here's what the connection code looks like: // OUTSIDE WHILE LOOPCharset charset =Charset.forName("ISO-8859-1");CharsetEncoder encoder = charset.newEncoder();// INSIDE if (channel.isConnectable())// Finish connectionif (keyChannel.isConnectionPending()) {keyChannel.finishConnect();}// Send requestString request = "GET / \n\r\n\r";keyChannel.write(encoder.encode(CharBuffer.wrap(request)));The reading from a socket channel is just like from a file channel. There is one exception though. It is more likely that the buffer may not be full when reading from a socket. Not a big deal though, as you are just going to read what is ready. // OUTSIDE WHILE LOOPCharsetDecoder decoder = charset.newDecoder();ByteBuffer buffer = ByteBuffer.allocateDirect(1024);CharBuffer charBuffer = CharBuffer.allocate(1024);// INSIDE if (channel.isReadable())// Read what's ready in responsekeyChannel.read(buffer);buffer.flip();// Decode bufferdecoder.decode(buffer, charBuffer, false);// DisplaycharBuffer.flip();System.out.print(charBuffer);// Clear for next passbuffer.clear();charBuffer.clear(); Add in the necessary exception handling code and you have your socket reader. Be sure to close the channel in the finally clause to make sure its resources are released, even if there is an exception. Here's the complete client code: import Java.io.*;import Java.net.*;import Java.nio.*;import Java.nio.channels.*;import Java.nio.charset.*;import Java.util.*;public class NonBlockingReadURL {static Selector selector;public static void main(String args[]) { String host = args[0]; SocketChannel channel = null; try {// SetupInetSocketAddress socketAddress =new InetSocketAddress(host, 80);Charset charset =Charset.forName("ISO-8859-1");CharsetDecoder decoder =charset.newDecoder();CharsetEncoder encoder =charset.newEncoder();// Allocate buffersByteBuffer buffer =ByteBuffer.allocateDirect(1024);CharBuffer charBuffer =CharBuffer.allocate(1024);// Connectchannel = SocketChannel.open();channel.configureBlocking(false);channel.connect(socketAddress);// Open Selectorselector = Selector.open();// Register interest in when connectionchannel.register(selector,SelectionKey.OP_CONNECT SelectionKey.OP_READ);// Wait for something of interest to happenwhile (selector.select(500) > 0) {// Get set of ready objectsSet readyKeys = selector.selectedKeys();Iterator readyItor = readyKeys.iterator();// Walk through setwhile (readyItor.hasNext()) { // Get key from set SelectionKey key = (SelectionKey)readyItor.next(); // Remove current entry readyItor.remove(); // Get channel SocketChannel keyChannel = (SocketChannel)key.channel(); if (key.isConnectable()) {// Finish connectionif (keyChannel.isConnectionPending()) {keyChannel.finishConnect();}// Send requestString request ="GET / \n\r\n\r";keyChannel.write(encoder.encode(CharBuffer.wrap(request))); } else if (key.isReadable()) {// Read what's ready in responsekeyChannel.read(buffer);buffer.flip();// Decode bufferdecoder.decode(buffer,charBuffer, false);// DisplaycharBuffer.flip();System.out.print(charBuffer);// Clear for next passbuffer.clear();charBuffer.clear(); } else {System.err.println("Ooops"); }}} } catch (UnknownHostException e) {System.err.println(e); } catch (IOException e) {System.err.println(e); } finally {if (channel != null) {try { channel.close();} catch (IOException ignored) {}} } System.out.println();}}Non-Blocking Servers
|