集册 Java实例教程 管理异步通信服务器

管理异步通信服务器

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

501
管理异步通信服务器

import java.io.IOException;

import java.net.InetSocketAddress;/** N  o w  J a v a . c o m 提供 **/

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.CompletionHandler;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;


public class Main {


  public static void main(String[] args) {

    try {

      final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open();

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

      listener.bind(address);


      listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {


        public void completed(AsynchronousSocketChannel channel, Void attribute) {
        /*
        N o w J a v a . c o m - 时  代  Java 提供
        */

          try {

            System.out.println("Server: completed method executing");

            while (true) {

              ByteBuffer buffer = ByteBuffer.allocate(32);

              Future<Integer> readFuture = channel.read(buffer);

              Integer number = readFuture.get();

              System.out.println("Server: Message received: " + new String(buffer.array()));

            }


          } catch (InterruptedException | ExecutionException ex) {

            ex.printStackTrace();

          }

        }


        public 
展开阅读全文