|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(12) The final piece is having a Web server use the NIO package. With the new I/O capabilities, you can create a Web server that does not require one thread per connection. You can certainly pool threads for long processing tasks, but all you have to do is select and wait for something to do, not have all the threads waiting separately. The basic setup of the server using channels involves you calling bind to connect a ServerSocketChannel to a InetSocketAddress. ServerSocketChannel channel =ServerSocketChannel.open();channel.configureBlocking(false);InetSocketAddress isa =new InetSocketAddress(port);channel.socket().bind(isa); Everything else is the same as the client reading, except this time you need to register the OP_ACCEPT key, and check for isAcceptable when the selector notifies you of the event. It is that simple. The following code example shows just how simple this is. It is your basic single-threaded server, sending back a canned text message for each request. Just use telnet to connect to port 9999 and see the response. import Java.io.*;import Java.net.*;import Java.nio.*;import Java.nio.channels.*;import Java.util.*;public class Server {private static int port = 9999;public static void main(String args[]) throws Exception { Selector selector = Selector.open(); ServerSocketChannel channel = ServerSocketChannel.open(); channel.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress(port); channel.socket().bind(isa); // Register interest in when connection channel.register(selector, SelectionKey.OP_ACCEPT); // Wait for something of interest to happen while (selector.select() > 0) {// Get set of ready objectsSet readyKeys = selector.selectedKeys();Iterator readyItor = readyKeys.iterator();// Walk through setwhile (readyItor.hasNext()) {// Get key from setSelectionKey key =(SelectionKey)readyItor.next();// Remove current entryreadyItor.remove();if (key.isAcceptable()) { // Get channel ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel(); // Accept request Socket socket = keyChannel.accept(); // Return canned message PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hello, NIO"); out.close();} else { System.err.println("Ooops");}} } // Never ends}}
|