Ejemplo n.º 1
0
 @Override
 public void completed(Integer i, ByteBuffer buf) {
   if (i > 0) {
     buf.flip();
     try {
       msg = decoder.decode(buf).toString();
       System.out.println("收到" + socket.getRemoteAddress().toString() + "的消息:" + msg);
       buf.compact();
     } catch (CharacterCodingException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
     socket.read(buf, buf, this);
     try {
       write(socket);
     } catch (UnsupportedEncodingException ex) {
       Logger.getLogger(AioReadHandler.class.getName()).log(Level.SEVERE, null, ex);
     }
   } else if (i == -1) {
     try {
       System.out.println("客户端断线:" + socket.getRemoteAddress().toString());
       buf = null;
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 2
0
 /**
  * close socket,remove socket from array
  *
  * @param socket
  */
 public static void closeConnection(AsynchronousSocketChannel socket) {
   try {
     logger.info("close client socket:" + socket.getRemoteAddress().toString());
     socket.close();
   } catch (IOException e) {
     logger.error("socket close error", e);
   }
   removeClientConnection(socket);
 }
Ejemplo n.º 3
0
 public FrontendConnection(AsynchronousSocketChannel channel) throws IOException {
   super(channel);
   InetSocketAddress localAddr = (InetSocketAddress) channel.getLocalAddress();
   InetSocketAddress remoteAddr = (InetSocketAddress) channel.getRemoteAddress();
   this.host = remoteAddr.getHostString();
   this.port = localAddr.getPort();
   this.localPort = remoteAddr.getPort();
   this.handler = new FrontendAuthenticator(this);
 }
Ejemplo n.º 4
0
 @Override
 public default void setOptions(AsynchronousSocketChannel channel) {
   try {
     channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
     channel.setOption(StandardSocketOptions.SO_RCVBUF, setRCV());
     channel.setOption(StandardSocketOptions.SO_SNDBUF, setSNF());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 5
0
 /** 显示所有active的连接 */
 public static void showAllConnections() {
   Enumeration<AsynchronousSocketChannel> it = allClientSocket.keys();
   while (it.hasMoreElements()) {
     AsynchronousSocketChannel so = it.nextElement();
     try {
       logger.info(so.getRemoteAddress().toString());
     } catch (IOException e) {
       logger.error("SocketQueue.showAllConnections IOException:", e);
     }
   }
 }
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
0
 @Override
 public void run() {
   latch = new CountDownLatch(1);
   client.connect(new InetSocketAddress(host, port), this, this);
   try {
     latch.await();
   } catch (InterruptedException e1) {
     e1.printStackTrace();
   }
   try {
     client.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 8
0
 @Override
 public void run() {
   try {
     while (true) {
       String message = null;
       try {
         message = context.getQueue().take();
       } catch (InterruptedException e) {
         log.warn("Can't read queue");
       }
       try {
         writeMessage(socket, message);
         readMessage(socket);
       } catch (Throwable e) {
         String warning = "Client disconected";
         try {
           warning += " ::: " + socket.getRemoteAddress();
         } catch (Throwable ex) {
           log.error("Unexpected error : " + ex.getMessage());
         }
         log.warn(warning);
         break;
       }
     }
   } catch (Throwable ex) {
     log.error("Unexpected error : " + ex.getMessage());
   } finally {
     shutdown();
   }
 }
Ejemplo n.º 9
0
    public void handle() {
      channel.read(
          buffer,
          channelWrapper,
          new CompletionHandler<Integer, Channel>() {
            @Override
            public void completed(Integer result, Channel attachment) {

              if (result != -1) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                getFilterChain().doReceive(attachment, bytes);
                buffer.clear();

                channel.read(buffer, attachment, this);
              } else {
                getFilterChain().doClose(attachment);
              }
            }

            @Override
            public void failed(Throwable exc, Channel attachment) {
              getFilterChain().doClose(attachment);
            }
          });
    }
 private String mapRemoteAddress(AsynchronousSocketChannel channel) {
   try {
     return channel.getRemoteAddress().toString();
   } catch (IOException e) {
     return "Unknown connection";
   }
 }
Ejemplo n.º 11
0
  @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
            }
          }
        });
  }
Ejemplo n.º 12
0
 public void shutdown() {
   try {
     socket.close();
     workers.remove(this);
   } catch (Exception e) {
     log.warn("Can't close worker ::: " + e.getMessage());
   }
 }
Ejemplo n.º 13
0
  public void start() throws Exception {
    client.connect(
        new InetSocketAddress("127.0.0.1", 8000),
        null,
        new CompletionHandler<Void, Void>() {
          @Override
          public void completed(Void result, Void attachment) {
            try {
              client.write(ByteBuffer.wrap("this is a test".getBytes())).get();
              System.out.println("send data to server");
            } catch (Exception ex) {
              ex.printStackTrace();
            }
          }

          @Override
          public void failed(Throwable exc, Void attachment) {
            exc.printStackTrace();
          }
        });
    final ByteBuffer bb = ByteBuffer.allocate(1024);
    client.read(
        bb,
        null,
        new CompletionHandler<Integer, Object>() {

          @Override
          public void completed(Integer result, Object attachment) {
            System.out.println(result);
            System.out.println(new String(bb.array()));
          }

          @Override
          public void failed(Throwable exc, Object attachment) {
            exc.printStackTrace();
          }
        });

    try {
      // Wait for ever
      Thread.sleep(Integer.MAX_VALUE);
    } catch (InterruptedException ex) {
      System.out.println(ex);
    }
  }
Ejemplo n.º 14
0
 public AsyncTimeClientHandler(String host, int port) {
   this.host = host;
   this.port = port;
   try {
     client = AsynchronousSocketChannel.open();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 15
0
 private boolean readMessage(AsynchronousSocketChannel socket) {
   boolean success = false;
   ByteBuffer readBuffer = ByteBuffer.allocate(4096);
   if (socket.isOpen()) {
     try {
       socket.read(readBuffer).get();
     } catch (InterruptedException | ExecutionException e) {
       readBuffer = null;
       throw new RuntimeException("Interupted");
     }
     byte[] data = readBuffer.array();
     if (data != null && data.length > 0) {
       processData(data);
       success = true;
     }
   }
   return success;
 }
Ejemplo n.º 16
0
 @Override
 public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
   exc.printStackTrace();
   try {
     client.close();
     latch.countDown();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 17
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));
    }
  }
Ejemplo n.º 18
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);
   }
 }
Ejemplo n.º 19
0
  public boolean update(long timeDiff) {
    if (channel != null) {
      if (!channel.isOpen()) {}
    }

    ProtocolPackage pack;
    while (!recvQueue.isEmpty()) {
      pack = recvQueue.remove(0);
      ProtocolRouter.getInstance().Trigger(pack.protocolId, pack, this);
    }
    return true;
  }
Ejemplo n.º 20
0
 public GameSession(String guid, AsynchronousSocketChannel c, long time) {
   this.guid = guid;
   channel = c;
   try {
     address = c.getRemoteAddress().toString();
   } catch (IOException e) {
     e.printStackTrace();
   }
   generateTime = time;
   heartBeatTime = time;
   recvQueue = new ArrayList<ProtocolPackage>();
   isDispose = false;
 }
Ejemplo n.º 21
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));
  }
Ejemplo n.º 22
0
 @Override
 public Result attempt(
     final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) {
   assert args.size() == 2;
   final AvailObject handle = args.get(0);
   final AvailObject options = args.get(1);
   final AvailObject pojo = handle.getAtomProperty(AtomDescriptor.socketKey());
   if (pojo.equalsNil()) {
     return interpreter.primitiveFailure(
         handle.isAtomSpecial() ? E_SPECIAL_ATOM : E_INVALID_HANDLE);
   }
   final AsynchronousSocketChannel socket = (AsynchronousSocketChannel) pojo.javaObjectNotNull();
   try {
     for (final MapDescriptor.Entry entry : options.mapIterable()) {
       final AvailObject key = entry.key();
       final AvailObject entryValue = entry.value();
       assert key != null;
       @SuppressWarnings("rawtypes")
       final SocketOption option = socketOptions[key.extractInt()];
       final Class<?> type = option.type();
       if (type.equals(Boolean.class) && entryValue.isBoolean()) {
         final SocketOption<Boolean> booleanOption = option;
         socket.setOption(booleanOption, entryValue.extractBoolean());
       } else if (type.equals(Integer.class) && entryValue.isInt()) {
         final Integer value = entryValue.extractInt();
         socket.<Integer>setOption(option, value);
       } else {
         return interpreter.primitiveFailure(E_INCORRECT_ARGUMENT_TYPE);
       }
     }
     return interpreter.primitiveSuccess(NilDescriptor.nil());
   } catch (final IllegalArgumentException e) {
     return interpreter.primitiveFailure(E_INCORRECT_ARGUMENT_TYPE);
   } catch (final IOException e) {
     return interpreter.primitiveFailure(E_IO_ERROR);
   }
 }
Ejemplo n.º 23
0
  @Override
  public synchronized void run() {
    while (true) {
      if (getSocket() == null) {
        try {
          this.wait();
        } catch (InterruptedException ignored) {

        }
      }

      ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
      socket.read(buffer, null, new SocketReadCompleteHandler(buffer, socket, this));

      threadPool.workComplete(this);
    }
  }
Ejemplo n.º 24
0
 public void dispose() {
   if (!isDispose) {
     isDispose = true;
   }
   if (player != null) {
     if (player.getCurrentHall() != null) {
       player.getCurrentHall().kickPlayer(this);
     }
     player = null;
   }
   if (readBuffer != null) {
     BufferPool.getInstance().releaseBuffer(readBuffer);
     readBuffer = null;
   }
   if (channel != null) {
     try {
       channel.close();
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       channel = null;
     }
   }
 }
Ejemplo n.º 25
0
 // 不是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));
 }
Ejemplo n.º 26
0
 private void accept(AsynchronousSocketChannel channel) throws IOException {
   LOGGER.info("======accept========" + channel.getRemoteAddress() + ";");
   ServerConnection serverConnection = new ServerConnection(GID_GENERATOR.getGid(), channel);
   serverConnection.regist();
 }
Ejemplo n.º 27
0
 public void startRecv() {
   if (channel.isOpen()) {
     readBuffer = BufferPool.getInstance().getBuffer();
     channel.read(readBuffer, this, AIOSocketMgr.getInstance().getReadHandler());
   }
 }
Ejemplo n.º 28
0
 public void makeResponse(AsynchronousSocketChannel socket, String response) {
   ByteBuffer buffer = ByteBuffer.wrap(response.getBytes());
   socket.write(buffer, null, new SocketWriteCompleteHandler(buffer, socket));
 }
Ejemplo n.º 29
0
  public static void main(String[] args) {

    final int DEFAULT_PORT = 5555;
    final String IP = "127.0.0.1";

    // create asynchronous socket channel bound to the default group
    try (AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open()) {

      if (asynchronousSocketChannel.isOpen()) {

        // set some options
        asynchronousSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
        asynchronousSocketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        asynchronousSocketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

        // connect this channel's socket
        asynchronousSocketChannel.connect(
            new InetSocketAddress(IP, DEFAULT_PORT),
            null,
            new CompletionHandler<Void, Void>() {

              final ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());
              final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
              CharBuffer charBuffer = null;
              ByteBuffer randomBuffer;
              final Charset charset = Charset.defaultCharset();
              final CharsetDecoder decoder = charset.newDecoder();

              @Override
              public void completed(Void result, Void attachment) {
                try {
                  System.out.println(
                      "Successfully connected at: " + asynchronousSocketChannel.getRemoteAddress());

                  // transmitting data
                  asynchronousSocketChannel.write(helloBuffer).get();

                  while (asynchronousSocketChannel.read(buffer).get() != -1) {

                    buffer.flip();

                    charBuffer = decoder.decode(buffer);
                    System.out.println(charBuffer.toString());

                    if (buffer.hasRemaining()) {
                      buffer.compact();
                    } else {
                      buffer.clear();
                    }

                    int r = new Random().nextInt(100);
                    if (r == 50) {
                      System.out.println(
                          "50 was generated! Close the asynchronous socket channel!");
                      break;
                    } else {
                      randomBuffer =
                          ByteBuffer.wrap("Random number:".concat(String.valueOf(r)).getBytes());
                      asynchronousSocketChannel.write(randomBuffer).get();
                    }
                  }
                } catch (IOException | InterruptedException | ExecutionException ex) {
                  System.err.println(ex);
                } finally {
                  try {
                    asynchronousSocketChannel.close();
                  } catch (IOException ex) {
                    System.err.println(ex);
                  }
                }
              }

              @Override
              public void failed(Throwable exc, Void attachment) {
                throw new UnsupportedOperationException("Connection cannot be established!");
              }
            });

        System.in.read();

      } else {
        System.out.println("The asynchronous socket channel cannot be opened!");
      }

    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Ejemplo n.º 30
0
 public EchoAioClient() throws Exception {
   client = AsynchronousSocketChannel.open();
 }