Create an asynchronous server socket channel bound to the default group - Java File Path IO

Java examples for File Path IO:File Channel

Description

Create an asynchronous server socket channel bound to the default group

Demo Code

import java.io.IOException;
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()) {/*from www  .  j  a va2 s . co  m*/
      if (asynChannel.isOpen()) {
        asynChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
        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!");
          } catch (IOException | InterruptedException | ExecutionException ex) {
            System.err.println(ex);
          }
        }
      } else {
        System.out
            .println("The asynchronous server-socket channel cannot be opened!");
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials