集册 Java实例教程 使用异步服务器套接字通道同时接受多个客户端

使用异步服务器套接字通道同时接受多个客户端

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

487
通过异步服务器套接字通道同时接受多个客户端

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;/* from n o w j a v a . c o m - 时代Java*/

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;


public class Main {

  public static void main(String[] args) {

    ExecutorService taskExecutor = Executors.newCachedThreadPool(Executors

        .defaultThreadFactory());

    try (AsynchronousServerSocketChannel asyncServerChannel = AsynchronousServerSocketChannel

        .open()) {

      if (asyncServerChannel.isOpen()) {

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

        asyncServerChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

        asyncServerChannel.bind(new InetSocketAddress("127.0.0.1", 5555));
        /**
        时代Java - N o w  J a v a . c o m 提供 
        **/

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


        while (true) {

          Future<AsynchronousSocketChannel> asynchFuture = asyncServerChannel

              .accept();


          try {

            final AsynchronousSocketChannel asyncChannel = asynchFuture.get();

            Callable<String> worker = new Callable<String>() {


              @Override

              public String call() throws Exception {


                String host = asyncChannel.getRemoteAddress().toString();

                System.out.println("Incoming connection from: " + host);


                final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);


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


                  buffer.flip();


                  asyncChannel.write(buffer).get();


                  if (buffer.hasRemaining()) {

                    buffer.compact();

                  } else {

                    buffer.clear();

                  }

                }


                asyncChannel.close();

                System.out.println(host + " was successfully served!");

                return host;

              }

            };

            taskExecutor.submit(worker);

          } catch (InterruptedException | ExecutionException ex) {

展开阅读全文