Exemplo n.º 1
0
 private boolean block() throws IOException {
   int numberOfKeysSelected = 0;
   if (blockInMilliseconds > 0) {
     numberOfKeysSelected = key.selector().select(blockInMilliseconds);
   } else if (blockInMilliseconds == 0) {
     numberOfKeysSelected = key.selector().selectNow();
   }
   return numberOfKeysSelected == 0;
 }
Exemplo n.º 2
0
 public void handleAccept(SelectionKey key) throws IOException {
   ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
   SocketChannel socketChannel = serverSocketChannel.accept();
   log.info("Server: accept client socket " + socketChannel);
   socketChannel.configureBlocking(false);
   socketChannel.register(key.selector(), SelectionKey.OP_READ);
 }
Exemplo n.º 3
0
 @GuardedBy("lock")
 private void setWriteOps() {
   // Make sure we are registered to get updated when writing is available again
   key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
   // Refresh the selector to make sure it gets the new interestOps
   key.selector().wakeup();
 }
Exemplo n.º 4
0
  private void startPoll(SelectionKey key) {

    System.out.println("about to poll on server");
    MessageStat messageStat = null;
    ServerSocketChannel so = null;
    SocketChannel sc = null;

    while (true) {
      try {
        if (key.selector().select() <= 0) {
          continue;
        }

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

        while (itr.hasNext()) {

          SelectionKey ready = itr.next();
          itr.remove();

          if (ready.isValid() && ready.isReadable()) {
            sc = (SocketChannel) ready.channel();
            messageStat = requestReader.read(sc);

            if (messageStat.isEndOfMessage()) {
              handle(sc, messageStat);
              sc.close();
              // TODO need to delete message stat entry ??
              // TODO with this way, Connection: keeyp-alive is meaningless ?
            }
          } else if (ready.isValid() && ready.isAcceptable()) {

            so = (ServerSocketChannel) key.channel();

            sc = so.accept();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
Exemplo n.º 5
0
  private SelectionKey checkIfSpinnedKey(final SelectionKey key) {
    if (!key.isValid()
        && key.channel().isOpen()
        && spinnedSelectorsHistory.containsKey(key.selector())) {
      final SelectionKey newKey = key.channel().keyFor(selector);
      newKey.attach(key.attachment());
      return newKey;
    }

    return key;
  }
Exemplo n.º 6
0
 @Override
 public void finishedReading(SelectionKey key) {
   ((AttachmentHTTP) serverChannel.keyFor(key.selector()).attachment()).fullWrittenBuffer = true;
   PoolClientConnectionManager.getInstance().removeClient(key);
   Statistics.getInstance().addMethod(httpRequest.getMethod());
   if (httpRequest.getHost() != null) {
     LoggingManager.logReport("REQ - " + httpRequest.getMethod() + " " + httpRequest.getHost());
   } else {
     LoggingManager.logError("REQ - " + httpRequest.getMethod() + " " + "Unkown host");
   }
 }
 public void close() {
   try {
     if (socketChannel != null) {
       socketChannel.close();
       socketChannel = null;
       if (selectionKey != null) selectionKey.selector().wakeup();
     }
   } catch (IOException ex) {
     if (DEBUG) debug("kryonet", "Unable to close TCP connection.", ex);
   }
 }
Exemplo n.º 8
0
 public void close() {
   connectedAddress = null;
   try {
     if (datagramChannel != null) {
       datagramChannel.close();
       datagramChannel = null;
       if (selectionKey != null) selectionKey.selector().wakeup();
     }
   } catch (IOException ex) {
     if (DEBUG) debug("hjh", "Unable to close UDP connection.", ex);
   }
 }
  /**
   * Cancel a SelectionKey
   *
   * @param key <tt>SelectionKey</tt> to cancel
   * @deprecated
   */
  public void cancelKey(SelectionKey key) {
    if (stateHolder.getState() == State.STOPPED) {
      return;
    }

    SelectorHandler selectorHandler = getSelectorHandler(key.selector());
    if (selectorHandler != null) {
      selectorHandler.getSelectionKeyHandler().cancel(key);
    } else {
      throw new IllegalStateException(
          "SelectionKey is not associated " + "with known SelectorHandler");
    }
  }
  /** This method is thread safe. */
  public int send(Connection connection, Object object) throws IOException {
    SocketChannel socketChannel = this.socketChannel;
    if (socketChannel == null) throw new SocketException("Connection is closed.");
    synchronized (writeLock) {
      // Leave room for length.
      int start = writeBuffer.position();
      int lengthLength = serialization.getLengthLength();
      writeBuffer.position(writeBuffer.position() + lengthLength);

      // Write data.
      try {
        serialization.write(connection, writeBuffer, object);
      } catch (KryoNetException ex) {
        throw new KryoNetException(
            "Error serializing object of type: " + object.getClass().getName(), ex);
      }
      int end = writeBuffer.position();

      // Write data length.
      writeBuffer.position(start);
      serialization.writeLength(writeBuffer, end - lengthLength - start);
      writeBuffer.position(end);

      // Write to socket if no data was queued.
      if (start == 0 && !writeToSocket()) {
        // A partial write, set OP_WRITE to be notified when more writing can occur.
        selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
      } else {
        // Full write, wake up selector so idle event will be fired.
        selectionKey.selector().wakeup();
      }

      if (DEBUG || TRACE) {
        float percentage = writeBuffer.position() / (float) writeBuffer.capacity();
        if (DEBUG && percentage > 0.75f)
          debug(
              "kryonet",
              connection + " TCP write buffer is approaching capacity: " + percentage + "%");
        else if (TRACE && percentage > 0.25f)
          trace("kryonet", connection + " TCP write buffer utilization: " + percentage + "%");
      }

      lastWriteTime = System.currentTimeMillis();
      return end - start;
    }
  }
Exemplo n.º 11
0
  /**
   * Accepts any incoming connections.
   *
   * @throws java.io.IOException
   */
  public static void accept(SelectionKey key) throws IOException {
    ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();

    // Accept the socket channel.
    SocketChannel channel = serverChannel.accept();
    if (channel == null) {
      return;
    }

    // Make sure we can allow this connection.
    if (!HostGateway.enter(channel.socket().getInetAddress().getHostAddress())) {
      channel.close();
      return;
    }

    // Set up the new connection.
    channel.configureBlocking(false);
    SelectionKey newKey = channel.register(key.selector(), SelectionKey.OP_READ);
    Player player = new Player(newKey);
    newKey.attach(player);
  }
Exemplo n.º 12
0
  public void onWrite(SelectionKey key) throws Exception {

    String accepts = req.headerString(Accept$2dEncoding);
    String ceString = null;
    String finalFname = scrub(rootPath + "/./" + req.path());
    file = new File(finalFname);
    if (null != accepts) {
      //              String accepts = UTF8.decode((ByteBuffer)
      // addHeaderInterest.clear().limit(ints[1]).position(ints[0])).toString().trim();
      for (CompressionTypes compType : CompressionTypes.values()) {
        if (accepts.contains(compType.name())) {
          File f = new File(finalFname + "." + compType.suffix);
          if (f.isFile() && f.canRead()) {

            if (BlobAntiPatternObject.DEBUG_SENDJSON)
              System.err.println("sending compressed archive: " + f.getAbsolutePath());
            ceString = (compType.name());
            file = f;
            break;
          }
        }
      }
    }
    boolean send200 = false;
    try {
      send200 = file.canRead() && file.isFile();
    } finally {

    }

    if (send200) {
      final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
      final long total = randomAccessFile.length();
      final FileChannel fileChannel = randomAccessFile.getChannel();

      String substring = finalFname.substring(finalFname.lastIndexOf('.') + 1);
      MimeType mimeType = MimeType.valueOf(substring);
      long length = randomAccessFile.length();

      final HttpResponse responseHeader = new Rfc822HeaderState().$res();

      responseHeader
          .status(HttpStatus.$200)
          .headerString(Content$2dType, (null == mimeType ? MimeType.bin : mimeType).contentType)
          .headerString(Content$2dLength, String.valueOf(length));
      if (null != ceString) responseHeader.headerString(Content$2dEncoding, ceString);
      ByteBuffer response = (ByteBuffer) responseHeader.as(ByteBuffer.class);
      int write = channel.write(response);
      final int sendBufferSize = BlobAntiPatternObject.getSendBufferSize();
      final long[] progress = {fileChannel.transferTo(0, sendBufferSize, channel)};
      key.interestOps(OP_WRITE | OP_CONNECT);
      key.selector().wakeup();
      key.attach(
          new Impl() {

            public void onWrite(SelectionKey key) throws Exception {
              long remaining = total - progress[0];
              progress[0] +=
                  fileChannel.transferTo(progress[0], min(sendBufferSize, remaining), channel);
              remaining = total - progress[0];
              if (0 == remaining) {
                fileChannel.close();
                randomAccessFile.close();
                key.selector().wakeup();
                key.interestOps(OP_READ);
                key.attach(null);
              }
            }
          });
    } else {
      key.selector().wakeup();
      key.interestOps(OP_WRITE)
          .attach(
              new Impl() {

                public void onWrite(SelectionKey key) throws Exception {

                  String response = "HTTP/1.1 404 Not Found\n" + "Content-Length: 0\n\n";
                  System.err.println("!!! " + file.getAbsolutePath());
                  int write = channel.write(UTF8.encode(response));
                  key.selector().wakeup();
                  key.interestOps(OP_READ).attach(null);
                }
              });
    }
  }
Exemplo n.º 13
0
 /** Notify Dispatcher Selector that we want write some data here. */
 protected final void enableWriteInterest() {
   if (key.isValid()) {
     key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
     key.selector().wakeup();
   }
 }