Java AsynchronousServerSocketChannel use Future object in a server

Description

Java AsynchronousServerSocketChannel use Future object in a server

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

public class Main {

   public static void main(String[] args) {
      try {//from w w  w.ja  va  2s  .  c om
         final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open();
         InetSocketAddress address = new InetSocketAddress("localhost", 5000);
         listener.bind(address);
         // 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);
            Integer number = readFuture.get();
            System.out.println(number);
            System.out.println("Server: Message received: " + new String(buffer.array()));
         }

      } catch (Exception ex) {

         ex.printStackTrace();
      }
   }
}



PreviousNext

Related