@Override
  public void completed(Void result, AsyncTimeClientHandler attachment) {
    byte[] req = "QUERY TIME ORDER".getBytes();
    ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
    writeBuffer.put(req);
    writeBuffer.flip();
    client.write(
        writeBuffer,
        writeBuffer,
        new CompletionHandler<Integer, ByteBuffer>() {
          @Override
          public void completed(Integer result, ByteBuffer buffer) {
            if (buffer.hasRemaining()) {
              client.write(buffer, buffer, this);
            } else {
              ByteBuffer readBuffer = ByteBuffer.allocate(1024);
              client.read(
                  readBuffer,
                  readBuffer,
                  new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer buffer) {
                      buffer.flip();
                      byte[] bytes = new byte[buffer.remaining()];
                      buffer.get(bytes);
                      String body;
                      try {
                        body = new String(bytes, "UTF-8");
                        System.out.println("Now is : " + body);
                        latch.countDown();
                      } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                      }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                      try {
                        client.close();
                        latch.countDown();
                      } catch (IOException e) {
                        // ingnore on close
                      }
                    }
                  });
            }
          }

          @Override
          public void failed(Throwable exc, ByteBuffer attachment) {
            try {
              client.close();
              latch.countDown();
            } catch (IOException e) {
              // ingnore on close
            }
          }
        });
  }
Exemple #2
0
  public void handle(ByteBuffer buffer, AsynchronousSocketChannel socket) {
    String path, method;

    String request = new String(buffer.array());

    try {
      path = getRequestPath(request);
      method = getRequestMethod(request);

      if (path == null || method == null) {
        throw new BadRequestException();
      }
      if (!method.equals("HEAD") && !method.equals("GET")) {
        makeResponse(socket, makeResponseHeader(METHOD_NOT_ALLOWED));
        return;
      }
    } catch (BadRequestException ignored) {
      makeResponse(socket, makeResponseHeader(BAD_REQUEST));
      return;
    }

    path = ROOT + path;
    File file = new File(path);
    try {
      if (!file.getCanonicalPath().contains(ROOT)) {
        makeResponse(socket, makeResponseHeader(FORBIDDEN));
        return;
      } else if (file.isDirectory()) {
        file = new File(path + File.separator + "index.html");
        if (!file.exists()) {
          makeResponse(socket, makeResponseHeader(FORBIDDEN));
          return;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (!file.exists()) {
      makeResponse(socket, makeResponseHeader(NOT_FOUND));
    }

    if (method.equals("GET")) {
      try {
        Response.readFile(this, socket, file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else if (method.equals("HEAD")) {
      ByteBuffer writeBuffer = ByteBuffer.wrap(getResponseHeader(file).getBytes());
      socket.write(writeBuffer, null, new SocketWriteCompleteHandler(writeBuffer, socket));
    }
  }
Exemple #3
0
  public void writeFile(AsynchronousSocketChannel socket, ByteBuffer buffer, String path) {
    String preparedHeader =
        Response.makeResponseHeader(OK, Response.getExtension(path), buffer.capacity());
    ByteBuffer wrappedHeader = ByteBuffer.wrap(preparedHeader.getBytes());
    buffer.flip();

    ByteBuffer fileResponse =
        ByteBuffer.allocate(buffer.capacity() + preparedHeader.length())
            .put(wrappedHeader)
            .put(buffer);
    fileResponse.position(0);
    socket.write(fileResponse, null, new SocketWriteCompleteHandler(fileResponse, socket));
  }
Exemple #4
0
 private boolean writeMessage(AsynchronousSocketChannel worker, String message) {
   boolean success = false;
   byte[] databytes = message.getBytes();
   ByteBuffer data = ByteBuffer.wrap(databytes);
   if (worker.isOpen()) {
     try {
       worker.write(data).get();
       success = true;
     } catch (InterruptedException | ExecutionException e) {
       data = null;
       throw new RuntimeException("Interupted");
     }
   }
   return success;
 }
Exemple #5
0
 public static void main(String[] args) throws Exception {
   try {
     AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
     InetSocketAddress address = new InetSocketAddress("localhost", Server1.PORT);
     Future<Void> future = client.connect(address);
     System.out.println("Client: Waiting for the connection to complete");
     future.get();
     String message;
     do {
       System.out.print("Enter a message: ");
       Scanner scanner = new Scanner(System.in);
       message = scanner.nextLine();
       System.out.println("Client: Sending ...");
       ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
       System.out.println("Client: Message sent: " + new String(buffer.array()));
       client.write(buffer);
     } while (!"quit".equals(message));
   } catch (InterruptedException e) {
     System.out.println(e);
   }
 }
Exemple #6
0
 public void makeResponse(AsynchronousSocketChannel socket, String response) {
   ByteBuffer buffer = ByteBuffer.wrap(response.getBytes());
   socket.write(buffer, null, new SocketWriteCompleteHandler(buffer, socket));
 }
  /**
   * @throws WritePendingException {@inheritDoc}
   * @throws NotYetConnectedException If this channel is not yet connected
   * @throws ShutdownChannelGroupException If the channel group has terminated
   */
  @Override
  public final <A> void write(
      ByteBuffer src, A attachment, CompletionHandler<Integer, ? super A> handler) {

    write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler);
  }
 // 不是CompletionHandler的方法
 public void write(AsynchronousSocketChannel socket) throws UnsupportedEncodingException {
   String sendString = "服务器回应,你输出的是:" + msg;
   ByteBuffer clientBuffer = ByteBuffer.wrap(sendString.getBytes("UTF-8"));
   socket.write(clientBuffer, clientBuffer, new AioWriteHandler(socket));
 }