Guest User

Untitled

a guest
Oct 17th, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.87 KB | None | 0 0
  1. // server
  2. public class AsyncHTTPServer {
  3.  
  4.     public static void main(String args[]) {
  5.         Map<String, String[]> config = null;
  6.         int port;
  7.         String documentRoot;
  8.         int cacheSize;
  9.         long timeout = 3000;
  10.  
  11.         try {
  12.             config = ServerUtil.readConfiguration(args);
  13.             try {
  14.                 // Required Arguments
  15.                 port = Integer.parseInt(config.get("Listen")[0]);
  16.                 documentRoot = config.get("DocumentRoot")[0];
  17.                 cacheSize = Integer.parseInt(config.get("CacheSize")[0]);
  18.             } catch (NullPointerException e) {
  19.                 throw new InvalidConfigException();
  20.             }
  21.             // Optional Arguments
  22.             String tmp[] = config.get("IncompleteTimeout");
  23.             timeout = (tmp == null) ? timeout : Integer.parseInt(tmp[0]);
  24.         } catch (InvalidConfigException e) {
  25.             System.err.println("Invalid Configuration or no config file.");
  26.             return;
  27.         }
  28.  
  29.         try {
  30.             Dispatcher d = new Dispatcher();
  31.             TimeoutThread t = new TimeoutThread(d, timeout);
  32.             Map<String, ByteBuffer> cache = new CacheMap<String, ByteBuffer>(
  33.                     cacheSize);
  34.  
  35.             ServerSocketChannel server = ServerSocketChannel.open();
  36.             server.socket().bind(new InetSocketAddress(port));
  37.             server.configureBlocking(false);
  38.             SocketReadWriteHandlerFactory s = new HTTPReadWriteHandlerFactory(
  39.                     documentRoot, "AsyncHTTPServer", cache);
  40.             AcceptHandler a = new HTTPAcceptHandler(server, d, s, t);
  41.             d.registerSelection(server, a, SelectionKey.OP_ACCEPT);
  42.             System.out.println("Listening at: " + port);
  43.            
  44.             new Thread(d).start();
  45.             t.start();
  46.         } catch (IOException e) {
  47.             System.err.println("Server initialization failed.");
  48.             e.printStackTrace();
  49.             return;
  50.         }
  51.  
  52.     }
  53. }
  54.  
  55. // dispatcher
  56. import java.io.IOException;
  57. import java.nio.channels.ClosedChannelException;
  58. import java.nio.channels.SelectableChannel;
  59. import java.nio.channels.SelectionKey;
  60. import java.nio.channels.Selector;
  61. import java.util.Iterator;
  62. import java.util.LinkedList;
  63. import java.util.Queue;
  64.  
  65. public class Dispatcher implements Runnable {
  66.     private Selector sel;
  67.     private Queue<DispatcherCommand> commandQueue;
  68.  
  69.     public Dispatcher() throws IOException {
  70.         try {
  71.             sel = Selector.open();
  72.         } catch (IOException e) {
  73.             System.err.println("Unable to open selector.");
  74.             return;
  75.         }
  76.         commandQueue = new LinkedList<DispatcherCommand>();
  77.     }
  78.  
  79.     public void registerSelection(SelectableChannel channel,
  80.             ChannelHandler handler, int ops) throws ClosedChannelException {
  81.         SelectionKey key = channel.register(sel, ops);
  82.         key.attach(handler);
  83.         return;
  84.     }
  85.  
  86.     public SelectionKey getKey(SelectableChannel channel) {
  87.         return channel.keyFor(sel);
  88.     }
  89.  
  90.     public void addCommand(DispatcherCommand cmd) {
  91.         synchronized (commandQueue) {
  92.             commandQueue.add(cmd);
  93.         }
  94.     }
  95.  
  96.     public void run() {
  97.         while (true) {
  98.             // Process events off the command queue first
  99.             synchronized (commandQueue) {
  100.                 while (!commandQueue.isEmpty()) {
  101.                     try {
  102.                         commandQueue.remove().run(this);
  103.                     } catch (Exception e) {
  104.                         System.err.println("Unable to execute command from queue.");
  105.                         e.printStackTrace();
  106.                         return;
  107.                     }
  108.                 }
  109.             }
  110.             try {
  111.                 sel.select();
  112.             } catch (IOException e) {
  113.                 System.err.println("I/O Error in Selector.");
  114.                 e.printStackTrace();
  115.                 return;
  116.             }
  117.            
  118.             Iterator<SelectionKey> it = sel.selectedKeys().iterator();
  119.  
  120.             while (it.hasNext()) {
  121.                 SelectionKey key = it.next();
  122.                 it.remove();
  123.                 ChannelHandler ch = (ChannelHandler) key.attachment();
  124.                 try {
  125.                     if (key.isAcceptable()) {
  126.                         AcceptHandler ah = (AcceptHandler)ch;
  127.                         ah.handleAccept(key);
  128.                     }
  129.  
  130.                     if (key.isReadable() || key.isWritable()) {
  131.                         SocketReadWriteHandler rwh = (SocketReadWriteHandler) ch;
  132.                         if (key.isReadable())
  133.                             rwh.handleRead(key);
  134.                         if (key.isWritable())
  135.                             rwh.handleWrite(key);
  136.                     }
  137.                 } catch (IOException e) {
  138.                     ch.handleException(key);
  139.                     e.printStackTrace();
  140.                 }
  141.             }
  142.  
  143.         }
  144.     }
  145. }
Advertisement
Add Comment
Please, Sign In to add comment