Advertisement
Guest User

Untitled

a guest
Jan 30th, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. public void listen() throws IOException {
  2.         long loopTime;
  3.         long timer = System.currentTimeMillis();
  4.         Log.log("Starting to listen for connections.", MessageState.ENGINE);
  5.         while(state == ServerState.RUNNING) {
  6.             loopTime = System.currentTimeMillis();
  7.             if(System.currentTimeMillis() - timer > 10000) {
  8.                 Log.log("*************************************\nCurrently there are " + connectionCount + " connections!\n*************************************", MessageState.ENGINE);
  9.                 timer = System.currentTimeMillis();
  10.             }
  11.            
  12.             selector.select(500);
  13.            
  14.             Iterator selectedKeys = selector.selectedKeys().iterator();
  15.             while(selectedKeys.hasNext()) {
  16.                 SelectionKey key = (SelectionKey) selectedKeys.next();
  17.                 selectedKeys.remove();
  18.                
  19.                 if(!key.isValid()) {
  20.                     continue;
  21.                 }
  22.                
  23.                 if(key.isAcceptable()) {
  24.                     accept(key);
  25.                     connectionCount++;
  26.                 } else if(key.isReadable()) {
  27.                     read(key);
  28.                 }
  29.             }
  30.            
  31.             loopTime = System.currentTimeMillis();
  32.             long engineUsage = (loopTime - timer < 1000) ? (loopTime - timer) / 10 : 100;
  33.             Log.log("Engine Usage: " + engineUsage + "%", MessageState.ENGINE);
  34.         }
  35.         serverSocket.close();
  36.         Log.log("Server ended...", MessageState.ENGINE);
  37.     }
  38.    
  39.     public void accept(SelectionKey key) throws IOException {
  40.         ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
  41.         SocketChannel socketChannel = serverSocketChannel.accept();
  42.         socketChannel.configureBlocking(false);
  43.         socketChannel.register(selector, SelectionKey.OP_READ);
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement