Created
September 15, 2017 18:57
-
-
Save nyg/dc1cbdc4e262b549fc3c01a7f509d42b to your computer and use it in GitHub Desktop.
Basic code example for AsynchronousServerSocketChannel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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