NIO

image.png

  1. public void run()
  2. {
  3. try {
  4. while (keepRunning) {
  5. doSelection (selector);
  6. }
  7. serverSocketChannel.close();
  8. selector.close();
  9. } catch (Exception e) {
  10. logger.fatal ("Unexpected exception: ", e);
  11. }
  12. }
  13. protected void doSelection (Selector selector)
  14. throws IOException
  15. {
  16. selector.select();
  17. if ( ! keepRunning) return;
  18. for (Iterator it = selector.selectedKeys().iterator(); it.hasNext();)
  19. {
  20. SelectionKey key = (SelectionKey) it.next();
  21. it.remove();
  22. if (key.isAcceptable()) {
  23. acceptNewConnection (key);
  24. continue;
  25. }
  26. Connection connection = (Connection) key.attachment();
  27. if (key.isWritable()) {
  28. connection.drainOutput();
  29. continue;
  30. }
  31. if (key.isReadable()) {
  32. connection.readInput();
  33. drainQueuedMessages (connection);
  34. continue;
  35. }
  36. }
  37. }
  38. protected void acceptNewConnection (SelectionKey serverKey)
  39. throws IOException
  40. {
  41. ServerSocketChannel serverSocketChannel =
  42. (ServerSocketChannel) serverKey.channel();
  43. SocketChannel socketChannel =
  44. serverSocketChannel.accept();
  45. User user = new GenericUser (null);
  46. socketChannel.configureBlocking (false);
  47. SelectionKey key = socketChannel.register (
  48. serverKey.selector(), SelectionKey.OP_READ);
  49. Connection connection = new NIOConnection (this,
  50. user, getProtocol(), key);
  51. key.attach (connection);
  52. connection.startup();
  53. }