集册 Java实例教程 创建绑定到默认组的异步服务器套接字通道

创建绑定到默认组的异步服务器套接字通道

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

435
创建绑定到默认组的异步服务器套接字通道

import java.io.IOException;
/*
N  o w  J a v a . c o m
*/

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;


public class Main {

  public static void main(String[] args) {

    try (AsynchronousServerSocketChannel asynChannel = AsynchronousServerSocketChannel

        .open()) {

      if (asynChannel.isOpen()) {

        asynChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);/**来 自 N o  w  J a v a . c o m - 时  代  Java**/

        asynChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

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

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

        while (true) {

          Future<AsynchronousSocketChannel> asynFuture = asynChannel.accept();

          try (AsynchronousSocketChannel asyncSocketChannel = asynFuture.get()) {

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

                + asyncSocketChannel.getRemoteAddress());


            final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

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

              buffer.flip();

              asyncSocketChannel.write(buffer).get();

              if (buffer.hasRemaining()) {

                buffer.compact();

              } else {

                buffer.clear();

              }

            }

            System.out.println(asyncSocketChannel.getRemoteAddress()

                + " was successfully served!");

          } 
展开阅读全文