Exemple #1
0
    private void serverSelected(SelectionKey key) {
      if (!key.isValid()) {
        return;
      }
      if (log.isDebugEnabled()) {
        log.debug("Server selected: a = {}", key.isAcceptable());
      }

      Context cx = Context.getCurrentContext();
      if (key.isAcceptable()) {
        SocketChannel child = null;
        do {
          try {
            child = svrChannel.accept();
            if (child != null) {
              if (log.isDebugEnabled()) {
                log.debug("Accepted new socket {}", child);
              }

              boolean success = false;
              try {
                getRunner().registerCloseable(child);
                TCPImpl sock = (TCPImpl) cx.newObject(this, CLASS_NAME);
                sock.initializeClient(child);
                if (onConnection != null) {
                  onConnection.call(cx, onConnection, this, new Object[] {sock});
                }
                success = true;
              } finally {
                if (!success) {
                  getRunner().unregisterCloseable(child);
                  try {
                    child.close();
                  } catch (IOException ioe) {
                    log.debug("Error closing channel that might be closed: {}", ioe);
                  }
                }
              }
            }
          } catch (ClosedChannelException cce) {
            log.debug("Server channel has been closed");
            break;
          } catch (IOException ioe) {
            log.error("Error accepting a new socket: {}", ioe);
          }
        } while (child != null);
      }
    }
  public void actionHandler(SelectionKey key) throws IOException {
    if (key.isAcceptable()) {
      ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
      SocketChannel socketChannel = serverChannel.accept();
      socketChannel.configureBlocking(false);
      socketChannel.register(roller, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      ByteBuffer buffer = ByteBuffer.allocate(16);
      SocketChannel socketChannel = (SocketChannel) key.channel();
      socketChannel.read(buffer);
      buffer.flip();
      String temp = decode(buffer);
      StringBuffer strBuffer = stringLocal.get();
      if (strBuffer == null) {
        strBuffer = new StringBuffer();
      }

      strBuffer.append(temp);

      if (temp.equals("\r\n")) {
        System.out.println(strBuffer.toString());
        strBuffer = null;
      }
      stringLocal.set(strBuffer);
    }
  }
  /**
   * Start the server running - accepting connections, receiving messages. If the server is already
   * running, it will not be started again. This method is designed to be called in its own thread
   * and will not return until the server is stopped.
   *
   * @throws RuntimeException if the server fails
   */
  public void run() {
    // ensure that the server is not started twice
    if (!state.compareAndSet(State.STOPPED, State.RUNNING)) {
      started(true);
      return;
    }

    Selector selector = null;
    ServerSocketChannel server = null;
    try {
      selector = Selector.open();
      server = ServerSocketChannel.open();
      server.socket().bind(new InetSocketAddress(port));
      server.configureBlocking(false);
      server.register(selector, SelectionKey.OP_ACCEPT);
      started(false);
      while (state.get() == State.RUNNING) {
        selector.select(100); // check every 100ms whether the server has been requested to stop
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
          SelectionKey key = it.next();
          try {
            // remove key from the ready list
            it.remove();
            if (key.isConnectable()) {
              ((SocketChannel) key.channel()).finishConnect();
            }
            if (key.isAcceptable()) {
              // accept connection
              SocketChannel client = server.accept();
              client.configureBlocking(false);
              client.socket().setTcpNoDelay(true);
              // channel is registered for further events such as read or write
              SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ);
              connection(acceptKey);
            }
            if (key.isReadable()) {
              for (ByteBuffer message : readIncomingMessage(key)) {
                messageReceived(message, key);
              }
            }
          } catch (IOException ioe) {
            resetKey(key);
            disconnected(key);
          }
        }
      }
    } catch (Throwable e) {
      throw new RuntimeException("Server failure: " + e.getMessage());
    } finally {
      try {
        selector.close();
        server.socket().close();
        server.close();
        state.set(State.STOPPED);
        stopped();
      } catch (Exception e) {
        // do nothing - server failed
      }
    }
  }
Exemple #4
0
  private void do_selection() throws IOException {
    // wait for events
    // timeout 1000ms -> check for pendingChanges at least every second
    if (selector.select(1000) == 0) return;

    // wakeup to work on selected keys
    Iterator keys = selector.selectedKeys().iterator();
    while (keys.hasNext()) {
      SelectionKey key = (SelectionKey) keys.next();
      keys.remove();

      if (!key.isValid()) {
        continue;
      }

      if (key.isAcceptable()) {
        accept(key);
      } else if (key.isReadable()) {
        read(key);
      } else if (key.isWritable()) {
        write(key);
      } else if (key.isConnectable()) {
        connect(key);
      }
    }
  }
  private void processEvent(final SelectionKey key) throws IOReactorException {
    try {

      if (key.isAcceptable()) {

        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel socketChannel = null;
        try {
          socketChannel = serverChannel.accept();
        } catch (IOException ex) {
          if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
            throw new IOReactorException("Failure accepting connection", ex);
          }
        }

        if (socketChannel != null) {
          try {
            prepareSocket(socketChannel.socket());
          } catch (IOException ex) {
            if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
              throw new IOReactorException("Failure initalizing socket", ex);
            }
          }
          ChannelEntry entry = new ChannelEntry(socketChannel);
          addChannel(entry);
        }
      }

    } catch (CancelledKeyException ex) {
      ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
      this.endpoints.remove(endpoint);
      key.attach(null);
    }
  }
  /**
   * Serves the incoming connections.
   *
   * @throws IOException
   * @throws DirectoryException
   */
  private void serveIncomingConnections() throws IOException, DirectoryException {
    int selectorState = selector.select();

    // We can't rely on return value of select to determine if any keys
    // are ready.
    // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4850373
    for (Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        iterator.hasNext(); ) {
      SelectionKey key = iterator.next();
      iterator.remove();
      if (key.isAcceptable()) {
        // Accept the new client connection.
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = serverChannel.accept();
        if (clientChannel != null) {
          acceptConnection(clientChannel);
        }
      }

      if (selectorState == 0 && enabled && !shutdownRequested && logger.isTraceEnabled()) {
        // Selected keys was non empty but select() returned 0.
        // Log warning and hope it blocks on the next select() call.
        logger.trace(
            "Selector.select() returned 0. "
                + "Selected Keys: %d, Interest Ops: %d, Ready Ops: %d ",
            selector.selectedKeys().size(), key.interestOps(), key.readyOps());
      }
    }
  }
Exemple #7
0
  /** Selects on sockets and informs their Communicator when there is something to do. */
  public void communicate(int timeout) {

    try {
      selector.select(timeout);
    } catch (IOException e) {
      // Not really sure why/when this happens yet
      return;
    }

    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

    while (keys.hasNext()) {
      SelectionKey key = keys.next();
      keys.remove();
      if (!key.isValid()) continue; // WHY
      Communicator communicator = (Communicator) key.attachment();

      if (key.isReadable()) communicator.onReadable();
      if (key.isWritable()) communicator.onWritable();
      if (key.isAcceptable()) communicator.onAcceptable();
    }

    // Go through the queue and handle each communicator
    while (!queue.isEmpty()) {
      Communicator c = queue.poll();
      c.onMemo();
    }
  }
  public static void main(String[] args) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
    System.out.println("Server listening at port : " + PORT);
    serverSocketChannel.configureBlocking(false);
    Selector selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
      int n = selector.select();
      if (n == 0) {
        continue;
      }
      Iterator<SelectionKey> it = selector.selectedKeys().iterator();
      while (it.hasNext()) {
        SelectionKey key = it.next();
        if (key.isAcceptable()) {
          ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
          SocketChannel sc = ssc.accept();
          sc.configureBlocking(false);
          sc.register(selector, SelectionKey.OP_READ);
          System.out.println("accept client : " + sc);
          acceptClient(sc);
        }
        if (key.isReadable()) {
          readData(key);
        }
        it.remove();
      }
    }
  }
 public void serve(int port) throws IOException {
   ServerSocketChannel serverChannel = ServerSocketChannel.open();
   serverChannel.configureBlocking(false);
   ServerSocket ss = serverChannel.socket();
   InetSocketAddress address = new InetSocketAddress(port);
   // Binds the server to the selected port
   ss.bind(address);
   // Opens the Selector for handling channels
   Selector selector = Selector.open();
   // Registers the ServerSocket with the Selector to accept connections
   serverChannel.register(selector, SelectionKey.OP_ACCEPT);
   final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
   while (true) {
     try {
       // Waits for new events to process; blocks until the next incoming event
       selector.select();
     } catch (IOException e) {
       e.printStackTrace();
       break;
     }
     // Obtains all SelectionKey instances that received events
     Set<SelectionKey> readyKeys = selector.selectedKeys();
     Iterator<SelectionKey> iterator = readyKeys.iterator();
     while (iterator.hasNext()) {
       SelectionKey key = iterator.next();
       iterator.remove();
       try {
         // Checks if the event is a new connection ready to be accepted
         if (key.isAcceptable()) {
           ServerSocketChannel server = (ServerSocketChannel) key.channel();
           SocketChannel client = server.accept();
           client.configureBlocking(false);
           // Accepts client and registers it with the selector
           client.register(
               selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate());
           System.out.println("Accepted connection from " + client);
         }
         // Checks if the socket is ready for writing data
         if (key.isWritable()) {
           SocketChannel client = (SocketChannel) key.channel();
           ByteBuffer buffer = (ByteBuffer) key.attachment();
           while (buffer.hasRemaining()) {
             // Writes data to the connected client
             if (client.write(buffer) == 0) {
               break;
             }
           }
           // Closes the connection
           client.close();
         }
       } catch (IOException e) {
         key.cancel();
         try {
           key.channel().close();
         } catch (IOException e1) {
         }
       }
     }
   }
 }
Exemple #10
0
 /**
  * This implementation defers to the {@link #accept(SelectionKey)} method if a connection is
  * pending. In all other cases it defers to it's parent.
  *
  * @param key The {@link SelectionKey} for the socket on which an I/O operation is pending.
  * @throws IOException if an error occurs while processing the pending event.
  */
 protected void handleSelectionKeyOperation(SelectionKey key) throws IOException {
   if (key.isValid() && key.isAcceptable()) {
     this.accept(key);
   } else {
     super.handleSelectionKeyOperation(key);
   }
 }
  @Override
  public void run() {
    try {
      System.out.println("[Server Opened]");
      selector = Selector.open();
      ssc.register(selector, SelectionKey.OP_ACCEPT);
      while (true) {
        int canalsPreparats = selector.select();
        if (canalsPreparats == 0) {
          continue;
        }
        Set<SelectionKey> clausSeleccionades = selector.selectedKeys();
        Iterator<SelectionKey> iterador = clausSeleccionades.iterator();
        while (iterador.hasNext()) {
          SelectionKey clau = iterador.next();

          // CONCURRENCIA claus
          // Les claus son un recurs compartit, ja que quan finalitza
          // el joc, el métode update() les cancela. Per aquest motiu
          // quan en fem us, synchronitzem el objecte, i comprovem
          // que siguin vàlides
          synchronized (this) {
            if (clau.isValid() && clau.isAcceptable()) {
              ferAccept(clau);
            } else if (clau.isValid() && clau.isReadable()) {
              rebre(clau);
            }
          }
          iterador.remove();
        }
      }
    } catch (IOException ex) {
    }
  }
  private void listen() throws IOException {
    while (true) {
      int selec = selector.select(500);

      if (selec == 0) {
        continue;
      }

      Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
      while (iterator.hasNext()) {
        SelectionKey selectionKey = iterator.next();
        try {
          iterator.remove();

          if (selectionKey.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);

            sc.register(selector, SelectionKey.OP_READ);
          } else if (selectionKey.isReadable()) {
            read(selectionKey);
          } else if (selectionKey.isWritable()) {
            write(selectionKey);
          }
        } catch (Exception e) {
          // iterator.remove(); Don't use it! It can throw a exception!
          SocketChannel sc = (SocketChannel) selectionKey.channel();
          sc.close();
        }
      }
    }
  }
  private void loop() {
    while (true) {
      try {
        selector.select();
        Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
          SelectionKey key = selectedKeys.next();
          selectedKeys.remove();

          if (!key.isValid()) {
            continue;
          }

          // Check what event is available and deal with it
          if (key.isAcceptable()) {
            accept(key);
          } else if (key.isReadable()) {
            read(key);
          } else if (key.isWritable()) {
            write(key);
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
      }
    }
  }
Exemple #14
0
  private void dispatchMessages() throws IOException {
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
      SelectionKey key = it.next();
      EventSource source = (EventSource) key.attachment();

      if (key.isValid()) {
        try {
          if (key.isAcceptable()) {
            EventSource newSource = source.accept();
            if (newSource != null) newSources.add(newSource);
          }

          if (key.isReadable()) {
            source.read();
          }

          if (key.isWritable()) {
            source.write();
          }
        } catch (CancelledKeyException e) {
        }
      }

      it.remove();
    }
    for (int i = 0; i < newSources.size(); i++) register(newSources.get(i));

    if (!newSources.isEmpty()) newSources.clear();
  }
  private void handle(SelectionKey key) throws IOException {
    // TODO Auto-generated method stub

    ServerSocketChannel server = null;
    SocketChannel client = null;
    String receiveText = null;
    int count = 0;

    if (key.isAcceptable()) {
      // client require accept events
      server = (ServerSocketChannel) key.channel();
      client = server.accept();
      client.configureBlocking(false);
      client.register(selector, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      // 如果是read事件,则直接读取
      client = (SocketChannel) key.channel();
      recBuffer.clear();
      count = client.read(recBuffer);
      if (count > 0) {
        recBuffer.flip();
        receiveText = decode.decode(recBuffer.asReadOnlyBuffer()).toString();
        System.out.println(client.toString() + ":" + receiveText);
        sendBuffer.clear();
        sendBuffer.put((sdf.format(new Date()) + "服务器收到你的消息").getBytes());
        sendBuffer.flip();
        client.write(sendBuffer);
        dispatch(client, receiveText);
        client = (SocketChannel) key.channel();
        client.register(selector, SelectionKey.OP_READ);
      }
    }
  }
Exemple #16
0
 public void run() {
   try {
     while (!flag) {
       System.out.println("waiting connected.......");
       selector.select();
       Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
       while (keys.hasNext()) {
         SelectionKey key = keys.next();
         keys.remove();
         if (key.isAcceptable()) {
           ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
           SocketChannel sc = ssc.accept();
           sc.configureBlocking(false);
           SelectionKey clientKey = sc.register(selector, SelectionKey.OP_READ);
           System.out.println(sc.socket().getInetAddress().getHostAddress() + " 已连接");
         }
         if (key.isReadable()) {
           read(key);
         }
       }
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemple #17
0
  public void run() {
    while (true) {
      try {
        synchronized (changeRequests) {
          Iterator changes = changeRequests.iterator();
          while (changes.hasNext()) {
            ChangeRequest change = (ChangeRequest) changes.next();
            switch (change.type) {
              case ChangeRequest.CHANGEOPS:
                SelectionKey key = change.socket.keyFor(selector);
                key.interestOps(change.ops);
            }
          }
          changeRequests.clear();
        }
        selector.select();

        Iterator selectedKeys = selector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
          SelectionKey key = (SelectionKey) selectedKeys.next();
          selectedKeys.remove();

          if (!key.isValid()) continue;

          if (key.isAcceptable()) accept(key);
          else if (key.isReadable()) read(key);
          else if (key.isWritable()) write(key);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  protected void onSelected(SelectionKey key) throws IOException {
    if (!key.isAcceptable()) {
      super.onSelected(key);
    } else if (!isOverloaded()) {
      try {
        // Accept the new connection
        SocketChannel socketChannel = getHelper().getServerSocketChannel().accept();

        if (socketChannel != null) {
          socketChannel.configureBlocking(false);
          getHelper().configure(socketChannel.socket());

          int connectionsCount = getHelper().getConnections().size();

          if ((getHelper().getMaxTotalConnections() == -1)
              || (connectionsCount <= getHelper().getMaxTotalConnections())) {
            Connection<Server> connection =
                getHelper()
                    .checkout(
                        socketChannel,
                        this,
                        (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress());
            connection.open();
            getHelper().getConnections().add(connection);

            if (getHelper().getLogger().isLoggable(Level.FINE)) {
              getHelper()
                  .getLogger()
                  .fine(
                      "Connection from \""
                          + connection.getSocketAddress()
                          + "\" accepted. New count: "
                          + getHelper().getConnections().size());
            }
          } else {
            // Rejection connection
            socketChannel.close();
            getHelper()
                .getLogger()
                .info("Maximum number of concurrent connections reached. New connection rejected.");
          }
        }
      } catch (ClosedByInterruptException ex) {
        getHelper().getLogger().log(Level.FINE, "ServerSocket channel was closed by interrupt", ex);
        throw ex;
      } catch (AsynchronousCloseException ace) {
        getHelper().getLogger().log(Level.FINE, "The server socket was closed", ace);
      } catch (SocketException se) {
        getHelper().getLogger().log(Level.FINE, "The server socket was closed", se);
      } catch (IOException ex) {
        getHelper()
            .getLogger()
            .log(Level.WARNING, "Unexpected error while accepting new connection", ex);
      }
    }
  }
    /**
     * Get the next SocketChannel in the operator we have built from the selected-key et for this
     * selector.
     *
     * @return The next SocketChannel in the iterator
     */
    public ServerSocketChannel next() {
      SelectionKey key = iterator.next();

      if (key.isValid() && key.isAcceptable()) {
        return (ServerSocketChannel) key.channel();
      }

      return null;
    }
  @Override
  protected void processKey(SelectionKey key) throws IOException {
    if (key.isAcceptable()) {
      if (key.channel() == commandServerChannel) {
        acceptCommand(key);
      } else {
        if (commandChannel == null) {
          throw new IOException("Unexpected");
        }

        accept(key);
      }
    } else {
      if (commandChannel == null) {
        throw new IOException("Unexpected");
      }

      if (key.isReadable() && pendingChannels.containsKey(key.channel())) {
        ByteChannel channel = (ByteChannel) key.channel();

        try {
          ByteBuffer readBuffer = pendingChannels.get(channel);
          int read = channel.read(readBuffer);
          if (read == -1) {
            throw new IOException("Pending channel closed");
          }

          if (readBuffer.position() >= 5) {
            readBuffer.flip();
            try {
              byte cmd = readBuffer.get();
              if (cmd == CMD_OPEN_CHANNEL_ACK) {
                int tunnelId = readBuffer.getInt();

                try {
                  registerLeftChannel(tunnelId, channel);
                  pendingChannels.remove(channel);
                } catch (IOException e) {
                  logger.log(Level.INFO, "Spooling error: " + e.getMessage(), e);
                  closeTunnel(tunnelId);
                }
              } else {
                throw new IOException("Unknown command");
              }
            } finally {
              readBuffer.compact();
            }
          }
        } catch (IOException e) {
          logger.log(Level.SEVERE, "PROTOCOL ERROR: " + e.getMessage(), e);
          close(channel);
        }
      } else {
        super.processKey(key);
      }
    }
  }
Exemple #21
0
 private void handle(SelectionKey key) throws Exception {
   if (key.isValid() && key.isAcceptable()) {
     ChannelHandler.handlerAccpet(server, key);
   } else if (key.isReadable()) {
     ChannelHandler.handlerRead(server, key);
   } else if (key.isWritable()) {
     ChannelHandler.handlerWrite(server, key);
   }
 }
Exemple #22
0
 /**
  * 处理accpect事件
  *
  * @param key
  */
 private void accept(SelectionKey key) {
   try {
     if (key.isValid() && key.isAcceptable())
       reactorPool.register(
           (SocketChannel)
               ((ServerSocketChannel) key.channel()).accept().configureBlocking(false));
     else key.cancel();
   } catch (IOException e) {
     logger.error(e.getMessage(), e);
   }
 }
  private void dispatch() throws IOException {
    SelectionKey key = null;
    for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) {
      key = request.getChannel().keyFor(selector);
      if (key != null) {
        // 写优先
        if ((request.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
          key.interestOps(SelectionKey.OP_WRITE);
          request.clearOps(SelectionKey.OP_WRITE);
        } else if ((request.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
          key.interestOps(SelectionKey.OP_READ);
          request.clearOps(SelectionKey.OP_READ);
        }
      }
    }

    isWeakuped.set(false);
    if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) {
      return;
    }

    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
      key = (SelectionKey) iterator.next();
      iterator.remove();
      try {
        if (!key.isValid()) {
          continue;
        } else if (key.isAcceptable()) {
          onAccept(key);
        } else if (key.isReadable()) {
          // readerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_READ));
          onRead(key);
        } else if (key.isWritable()) {
          // writerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_WRITE));
          onWrite(key);
        }
      } catch (IOException e) {
        // 客户端连接出问题
        Session session = (Session) key.attachment();
        if (session != null) {
          session.onException();
          // 释放Session
          sessionManager.freeSession(session);
        }
        opsChangeRequstMap.remove((SocketChannel) key.channel());
        key.cancel();
        key.channel().close();
        e.printStackTrace();
        logger.error("OOPS:Exception:", e);
      }
    }
  }
 public void serve(int port) throws IOException {
   ServerSocketChannel serverChannel = ServerSocketChannel.open();
   serverChannel.configureBlocking(false);
   ServerSocket ss = serverChannel.socket();
   InetSocketAddress address = new InetSocketAddress(port);
   ss.bind(address); // 2
   Selector selector = Selector.open(); // 2
   serverChannel.register(selector, SelectionKey.OP_ACCEPT); // 3
   final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
   for (; ; ) {
     try {
       selector.select(); // 4
     } catch (IOException ex) {
       ex.printStackTrace();
       // handle exception
       break;
     }
     Set<SelectionKey> readyKeys = selector.selectedKeys(); // 5
     Iterator<SelectionKey> iterator = readyKeys.iterator();
     while (iterator.hasNext()) {
       SelectionKey key = iterator.next();
       iterator.remove();
       try {
         if (key.isAcceptable()) { // 6
           ServerSocketChannel server = (ServerSocketChannel) key.channel();
           SocketChannel client = server.accept();
           client.configureBlocking(false);
           client.register(
               selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate()); // 7
           System.out.println("Accepted connection from " + client);
         }
         if (key.isWritable()) { // 8
           SocketChannel client = (SocketChannel) key.channel();
           ByteBuffer buffer = (ByteBuffer) key.attachment();
           while (buffer.hasRemaining()) {
             if (client.write(buffer) == 0) { // 9
               break;
             }
           }
           client.close(); // 10
         }
       } catch (IOException ex) {
         key.cancel();
         try {
           key.channel().close();
         } catch (IOException cex) {
           // ignore on close
         }
       }
     }
   }
 }
Exemple #25
0
  private void handleSelecedKeys() throws IOException {
    SocketChannel socketChannelForClient;

    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
    while (iter.hasNext()) {
      SelectionKey selectionKey = iter.next();

      // 判断事件类型
      if (selectionKey.isAcceptable()) { // 请求连接事件
        System.out.println("[** NIOServer **]: Handle a acceptable event!");
        socketChannelForClient = serverSocketChannel.accept();
        socketChannelForClient.configureBlocking(false);

        String responseMsg =
            "[$#$ From NIOServer $#$]: You has connected to server on " + bindLocalPort;
        byteBuffer.put(responseMsg.getBytes());
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
          socketChannelForClient.write(byteBuffer);
        }
        byteBuffer.clear();
        socketChannelForClient.register(selector, SelectionKey.OP_READ);

      } else if (selectionKey.isConnectable()) { // 连接事件
        System.out.println("[** NIOServer **]: Handle a connectable event!");

      } else if (selectionKey.isReadable()) { // 读事件
        System.out.println("[** NIOServer **]: Handle a readable event!");

        byte[] msg = readMessage(selectionKey);
        int size = 0;
        for (int i = 0; i < msg.length; i++) {
          if (msg[i] == 0) {
            size = i;
            break;
          } else if (i == msg.length - 1) {
            size = msg.length;
          }
        }

        System.out.println("[** NIOServer **]: Got a message: \"" + new String(msg) + "\" \n");

        sendMessage(selectionKey, "[$$ From NIOServer $$]: Got data size:" + size + "b !");

      } else if (selectionKey.isWritable()) { // 写事件
        System.out.println("[** NIOServer **]: Handle a writable event!");
      }

      // 移除已经处理过的事件, 避免重复处理
      iter.remove();
    }
  }
  void processIO() {
    Iterator<SelectionKey> it = mySelector.selectedKeys().iterator();
    while (it.hasNext()) {
      SelectionKey k = it.next();
      it.remove();

      if (k.isConnectable()) isConnectable(k);
      else if (k.isAcceptable()) isAcceptable(k);
      else {
        if (k.isWritable()) isWritable(k);

        if (k.isReadable()) isReadable(k);
      }
    }
  }
 public static void main(String[] args) throws Exception {
   SocketChannel sc = SocketChannel.open();
   Selector sel = Selector.open();
   if (sc.keyFor(sel) != null) throw new Exception("keyFor != null");
   sc.configureBlocking(false);
   SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
   if (sc.keyFor(sel) != sk) throw new Exception("keyFor returned " + sc.keyFor(sel));
   if (sk.attachment() != args) throw new Exception("attachment() returned " + sk.attachment());
   Trivial t = new Trivial();
   sk.attach(t);
   if (sk.attachment() != t) throw new Exception("Wrong attachment");
   sk.isReadable();
   sk.isWritable();
   sk.isConnectable();
   sk.isAcceptable();
 }
Exemple #28
0
  public void listener() {

    try {
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ServerSocket server = ssc.socket();
      Selector selector = Selector.open();

      server.bind(new InetSocketAddress(port));
      ssc.configureBlocking(false);
      ssc.register(selector, SelectionKey.OP_ACCEPT);

      while (true) {
        selector.select();
        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();

        while (it.hasNext()) {
          SelectionKey key = (SelectionKey) it.next();

          if (key.isAcceptable()) {
            Socket listen = server.accept();
            SocketChannel sc = listen.getChannel();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);
          }

          if (key.isReadable() && key.isValid()) {
            ByteBuffer bb = ByteBuffer.allocate(512);
            SocketChannel st = (SocketChannel) key.channel();
            int byteRead = st.read(bb);
            bb.flip();
            if (byteRead == -1) {
              key.cancel();
              st.close();

            } else {
              analyseData(bb);
              key.cancel();
            }
          }
        }
        keys.clear();
      }
    } catch (Exception e) {
    }
  }
Exemple #29
0
  public void frameProcess() throws IOException {
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
      SelectionKey selectionKey = iterator.next();
      iterator.remove();
      if (selectionKey.isAcceptable()) {
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
      }

      if (selectionKey.isReadable()) {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        onReadRequests(socketChannel);
      }
    }
  }
Exemple #30
0
 // 处理请求
 private void handleKey(SelectionKey selectionKey) throws IOException {
   // 接受请求
   ServerSocketChannel server = null;
   SocketChannel client = null;
   String receiveText;
   String sendText;
   int count = 0;
   // 测试此键的通道是否已准备好接受新的套接字连接。
   if (selectionKey.isAcceptable()) {
     // 返回为之创建此键的通道。
     server = (ServerSocketChannel) selectionKey.channel();
     // 接受到此通道套接字的连接。
     // 此方法返回的套接字通道(如果有)将处于阻塞模式。
     client = server.accept();
     // 配置为非阻塞
     client.configureBlocking(false);
     // 注册到selector,等待连接
     client.register(selector, SelectionKey.OP_READ);
   } else if (selectionKey.isReadable()) {
     // 返回为之创建此键的通道。
     client = (SocketChannel) selectionKey.channel();
     // 将缓冲区清空以备下次读取
     receivebuffer.clear();
     // 读取服务器发送来的数据到缓冲区中
     count = client.read(receivebuffer);
     if (count > 0) {
       receiveText = new String(receivebuffer.array(), 0, count);
       System.out.println("服务器端接受客户端数据--:" + receiveText);
       client.register(selector, SelectionKey.OP_WRITE);
     }
   } else if (selectionKey.isWritable()) {
     // 将缓冲区清空以备下次写入
     sendbuffer.clear();
     // 返回为之创建此键的通道。
     client = (SocketChannel) selectionKey.channel();
     sendText = "message from server--" + flag++;
     // 向缓冲区中输入数据
     sendbuffer.put(sendText.getBytes());
     // 将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位
     sendbuffer.flip();
     // 输出到通道
     client.write(sendbuffer);
     System.out.println("服务器端向客户端发送数据--:" + sendText);
     client.register(selector, SelectionKey.OP_READ);
   }
 }