Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 22nd, 2012  |  syntax: None  |  size: 4.83 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Asynchronous server using Java NIO
  2. package server;
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.InetSocketAddress;
  6. import java.net.Socket;
  7. import java.nio.ByteBuffer;
  8. import java.nio.channels.SelectionKey;
  9. import java.nio.channels.Selector;
  10. import java.nio.channels.ServerSocketChannel;
  11. import java.nio.channels.SocketChannel;
  12. import java.nio.channels.spi.SelectorProvider;
  13. import java.util.*;
  14.  
  15. import javax.xml.parsers.ParserConfigurationException;
  16.  
  17. import org.xml.sax.SAXException;
  18.  
  19. public class NioServer implements Runnable {
  20.  
  21.  
  22.  
  23. // The host:port combination to listen on
  24.   private InetAddress hostAddress;
  25.   private int port;
  26.  
  27.   // The channel on which we'll accept connections
  28.   private ServerSocketChannel serverChannel;
  29.  
  30.   // The selector we'll be monitoring
  31.   private Selector selector;
  32.  
  33.   //the cach will hundle the messages that came
  34.   private Cache cache;
  35.  
  36.   // The buffer into which we'll read data when it's available
  37.   private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
  38.  
  39.   public NioServer(InetAddress hostAddress, int port , Cache cache) throws IOException {
  40.     this.cache = cache;
  41.     this.hostAddress = hostAddress;
  42.     this.port = port;
  43.     this.selector = this.initSelector();
  44.   }
  45.  
  46.  
  47.   private Selector initSelector() throws IOException {
  48.         // Create a new selector
  49.         Selector socketSelector = SelectorProvider.provider().openSelector();
  50.  
  51.         // Create a new non-blocking server socket channel
  52.         this.serverChannel = ServerSocketChannel.open();
  53.         serverChannel.configureBlocking(false);
  54.  
  55.         // Bind the server socket to the specified address and port
  56.         InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
  57.         serverChannel.socket().bind(isa);
  58.  
  59.         // Register the server socket channel, indicating an interest in
  60.         // accepting new connections
  61.         serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
  62.  
  63.         return socketSelector;
  64.       }
  65.  
  66.   private void accept(SelectionKey key) throws IOException {
  67.         // For an accept to be pending the channel must be a server socket channel.
  68.         ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
  69.  
  70.         // Accept the connection and make it non-blocking
  71.         SocketChannel socketChannel = serverSocketChannel.accept();
  72.         Socket socket = socketChannel.socket();
  73.         socketChannel.configureBlocking(false);
  74.  
  75.         // Register the new SocketChannel with our Selector, indicating
  76.         // we'd like to be notified when there's data waiting to be read
  77.         socketChannel.register(this.selector, SelectionKey.OP_READ);
  78.       }
  79.  
  80.   private void read(SelectionKey key) throws IOException {
  81.         SocketChannel socketChannel = (SocketChannel) key.channel();
  82.  
  83.         // Clear out our read buffer so it's ready for new data
  84.         this.readBuffer.clear();
  85.  
  86.         // Attempt to read off the channel
  87.         int numRead;
  88.         try {
  89.           numRead = socketChannel.read(this.readBuffer);
  90.           String test = new String(this.readBuffer.array());
  91.           System.out.print(test);
  92.  
  93.         } catch (IOException e) {
  94.           // The remote forcibly closed the connection, cancel
  95.           // the selection key and close the channel.
  96.         //  key.cancel();
  97.         //  socketChannel.close();
  98.           return;
  99.         }
  100.  
  101.         if (numRead == -1) {
  102.           // Remote entity shut the socket down cleanly. Do the
  103.           // same from our end and cancel the channel.
  104.           key.channel().close();
  105.           key.cancel();
  106.           return;
  107.         }
  108.  
  109.         // Hand the data off to our worker thread
  110.         this.cache.processData(this, socketChannel, this.readBuffer.array(), numRead);
  111.       }
  112.  
  113.   public void run() {
  114.         while (true) {
  115.           try {
  116.             // Wait for an event one of the registered channels
  117.  
  118.             this.selector.select();
  119.  
  120.  
  121.  
  122.             // Iterate over the set of keys for which events are available
  123.             Iterator selectedKeys = this.selector.selectedKeys().iterator();
  124.             while (selectedKeys.hasNext()) {
  125.               SelectionKey key = (SelectionKey) selectedKeys.next();
  126.               selectedKeys.remove();
  127.  
  128.               if (!key.isValid()) {
  129.                 continue;
  130.               }
  131.  
  132.               // Check what event is available and deal with it
  133.               if (key.isAcceptable()) {
  134.                 this.accept(key);
  135.               } else if (key.isReadable()) {
  136.                 this.read(key);
  137.               }
  138.             }
  139.           } catch (Exception e) {
  140.             e.printStackTrace();
  141.           }
  142.         }
  143.       }
  144.  
  145.   public static void main(String[] args) throws ParserConfigurationException, SAXException {
  146.     try {
  147.         Cache cache = new Cache();
  148.         new Thread(cache).start();
  149.       new Thread(new NioServer(null, 9090,cache)).start();
  150.     } catch (IOException e) {
  151.       e.printStackTrace();
  152.     }
  153.   }