Skip to content

Instantly share code, notes, and snippets.

@nyg
Created September 15, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyg/dc1cbdc4e262b549fc3c01a7f509d42b to your computer and use it in GitHub Desktop.
Save nyg/dc1cbdc4e262b549fc3c01a7f509d42b to your computer and use it in GitHub Desktop.
Basic code example for AsynchronousServerSocketChannel.
AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(ip, port));
while (true) {
Future<AsynchronousSocketChannel> future = listener.accept();
AsynchronousSocketChannel channel = future.get();
ByteBuffer buffer = ByteBuffer.allocate(5000);
Future<Integer> byteCount = channel.read(buffer);
System.out.println("Bytes read: " + byteCount.get());
System.out.println(new String(buffer.array()));
String content = "Hello World!";
String response = "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: " + content.length() + "\n\n" + content;
byte[] responseBytes = response.getBytes();
ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
byteCount = channel.write(responseBuffer);
System.out.println("Bytes written: " + byteCount.get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment