集册 Java实例教程 基于CompletionHandler编写异步服务器

基于CompletionHandler编写异步服务器

欢马劈雪     最近更新时间:2020-01-02 10:19:05

419
编写基于CompletionHandler的异步服务器

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;//时 代 J a v a 公 众 号 - N o w J a v  a . c o m

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.CompletionHandler;

import java.util.concurrent.ExecutionException;


public class Main {

  public static void main(String[] args) {

    try (AsynchronousServerSocketChannel asynServerChannel = AsynchronousServerSocketChannel

        .open()) {

      if (asynServerChannel.isOpen()) {

        asynServerChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);

        asynServerChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

        asynServerChannel.bind(new InetSocketAddress("127.0.0.1", 5555));

        System.out.println("Waiting for connections ...");

        asynServerChannel.accept(null,
        /* 
         来自 
        *N o  w  J a v a . c o m - 时  代  Java*/

            new CompletionHandler<AsynchronousSocketChannel, Void>() {

              final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

              @Override

              public void completed(AsynchronousSocketChannel result,

                  Void attachment) {

                asynServerChannel.accept(null, this);

                try {

                  System.out.println("Incoming connection from: "

                      + result.getRemoteAddress());

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

                    buffer.flip();

                    result.write(buffer).get();

                    if (buffer.hasRemaining()) {

                      buffer.compact();

                    } else {

                      buffer.clear();

                    }

                  }

                } catch (Exception ex) {

                  System.err.println(ex);

                } finally {

                  try {

                    result.close();

                  } catch (IOException e) {

                    System.err.println(e);

                  }

                }

              }


              @Override

              public void failed(Throwable exc, Void attachment) {

                asynServerChannel.acce
展开阅读全文