集册 Java实例教程 了解AsynchronousServerSocketCannel类选项

了解AsynchronousServerSocketCannel类选项

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

450
了解AsynchronousServerSocketCannel类选项

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.SocketOption;

import java.nio.ByteBuffer;
/**
nowjava.com 提供 
**/

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.util.Set;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;


public class Main {


  public static void main(String[] args) {

    try {// 来自 N o w J a v a . c o m

      final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open();

      InetSocketAddress address = new InetSocketAddress("localhost", 5000);

      listener.bind(address);


      Set<SocketOption<?>> options = listener.supportedOptions();

      for (SocketOption<?> socketOption : options) {

        System.out.println(socketOption.toString() + ": " + listener.getOption(socketOption));

      }

      // Using the Future object in a server

      Future<AsynchronousSocketChannel> future = listener.accept();

      AsynchronousSocketChannel worker = future.get();


      while (true) {

        // Wait

        System.out.println("Server: Receiving ...");

        ByteBuffer buffer = ByteBuffer.allocate(32);

        Future<Integer> readFuture = worker.read(buffer
展开阅读全文