Esempio n. 1
0
  /** Handle a read event from a socket specified by the key. */
  private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    SocketAddress remoteAdr = socketChannel.socket().getRemoteSocketAddress();

    // Clear out our read buffer so it's ready for new data
    readBuffer.clear();

    // Attempt to read off the channel
    int numRead;
    try {
      numRead = socketChannel.read(readBuffer);
    } catch (IOException e) {
      // The remote forcibly closed the connection, cancel
      // the selection key and close the channel.
      key.cancel();
      socketChannel.close();
      clients.remove(remoteAdr);
      pendingWriteData.remove(socketChannel);
      logger.fine(
          "Connection forcibly closed("
              + remoteAdr
              + ")! Remaining connections: "
              + clients.size());
      throw new IOException("Remote forcibly closed the connection");
    }

    if (numRead == -1) {
      // Remote entity shut the socket down cleanly. Do the
      // same from our end and cancel the channel.
      key.channel().close();
      key.cancel();
      clients.remove(remoteAdr);
      pendingWriteData.remove(socketChannel);
      logger.fine("Connection Closed(" + remoteAdr + ")! Remaining connections: " + clients.size());
      throw new IOException("Remote closed the connection");
    }

    // Make a correctly sized copy of the data before handing it to the client
    // byte[] rspByteData = new byte[numRead];
    // System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead);

    try {
      Object rspData = Converter.toObject(readBuffer.array());

      // Hand the data off to our worker thread
      if (worker != null) {
        logger.finer("Handling incoming message...");
        worker.processData(this, socketChannel.getRemoteAddress(), rspData);
      } else {
        logger.fine("No worker set, message unhandled!");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 2
0
 public void send(SocketAddress address, Object data) throws IOException {
   send(address, Converter.toBytes(data));
 }