Using the Future object in a server with Asynchronous Communication Server - Java Network

Java examples for Network:Asynchronous Server

Description

Using the Future object in a server with Asynchronous Communication Server

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Main {

    public static void main(String[] args) {
        try {/*w ww .  jav a  2  s . c  om*/
            final AsynchronousServerSocketChannel listener =
                    AsynchronousServerSocketChannel.open();
            InetSocketAddress address = new InetSocketAddress("localhost", 5000);
            listener.bind(address);

            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("Server: Message received: " + new String(buffer.array()));
            }
        } catch (IOException | InterruptedException | ExecutionException ex) {
              ex.printStackTrace();
        }
    }
}

Related Tutorials