Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.ByteBuffer;
- import java.nio.channels.AsynchronousServerSocketChannel;
- import java.nio.channels.AsynchronousSocketChannel;
- import java.nio.channels.CompletionHandler;
- import java.nio.charset.StandardCharsets;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.concurrent.ExecutionException;
- public class GeneralAioEchoServer {
- private AsynchronousServerSocketChannel assc;
- public static void main(String[] args) throws Exception {
- GeneralAioEchoServer server = new GeneralAioEchoServer();
- server.start();
- System.out.println("歡迎來到胖世界");
- while (true) {
- Thread.sleep(5000L);
- }
- }
- private void start() throws IOException {
- assc = AsynchronousServerSocketChannel.open();
- assc.bind(new InetSocketAddress(4000));
- assc.accept(null, new AcceptHandler());
- }
- private class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Object> {
- @Override
- public void completed(AsynchronousSocketChannel asc, Object o) {
- assc.accept(null, this);
- try {
- asc.write(StandardCharsets.UTF_8.encode("歡迎來到胖世界")).get();
- } catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
- }
- ByteBuffer bb = ByteBuffer.allocate(1024);
- asc.read(bb, null, new ReadHandler(asc, bb));
- }
- @Override
- public void failed(Throwable throwable, Object o) {
- }
- }
- private class ReadHandler implements CompletionHandler<Integer, Object> {
- private AsynchronousSocketChannel asc;
- private ByteBuffer bb;
- private ByteArrayOutputStream baos = new ByteArrayOutputStream();
- public ReadHandler(AsynchronousSocketChannel asc, ByteBuffer bb) {
- this.asc = asc;
- this.bb = bb;
- }
- @Override
- public void completed(Integer result, Object o) {
- long start = System.currentTimeMillis();
- if (result == -1) return;
- // read all bytes start
- byte[] bytes = new byte[bb.flip().limit()];
- bb.get(bytes).clear();
- Queue<String> inputs = new LinkedList<>();
- for (byte b : bytes) {
- if (b != '\n') {
- baos.write(b);
- } else {
- inputs.add(new String(baos.toByteArray(), StandardCharsets.UTF_8));
- baos.reset();
- }
- }
- // read all bytes end
- asc.read(bb, null, this);
- long end = System.currentTimeMillis() - start;
- System.out.println("total time = " + end);
- }
- @Override
- public void failed(Throwable throwable, Object o) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement