Skip to content

Instantly share code, notes, and snippets.

@liweinan
Last active July 14, 2017 01:04
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 liweinan/872159a8fc9207b2fe20fec7e22a5588 to your computer and use it in GitHub Desktop.
Save liweinan/872159a8fc9207b2fe20fec7e22a5588 to your computer and use it in GitHub Desktop.
package nio.sandbox;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* Created by weinanli on 14/07/2017.
*/
public class SocketReadWrite {
private static Selector _selector;
private static ByteBuffer _buffer = ByteBuffer.allocateDirect(1024);
public static void main(String[] args) throws Exception {
_selector = Selector.open();
ServerSocketChannel channel = ServerSocketChannel.open();
channel.socket().bind(new InetSocketAddress(8080));
channel.configureBlocking(false);
channel.register(_selector, SelectionKey.OP_ACCEPT);
while (!Thread.interrupted()) {
_selector.select();
Set keys = _selector.selectedKeys();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) (iterator.next());
if (key.isAcceptable()) {
acceptRequestAndRegisterReadEvent(key);
}
if (key.isReadable()) {
readRequestAndEcho(key);
}
iterator.remove();
}
}
}
private static void readRequestAndEcho(SelectionKey key) throws IOException {
SocketChannel _channel = (SocketChannel) key.channel();
_buffer.clear();
int count = 0;
while ((count = _channel.read(_buffer)) > 0) {
_buffer.flip();
while(_buffer.hasRemaining()) {
_channel.write(_buffer); // echo
}
}
_buffer.clear();
}
private static void acceptRequestAndRegisterReadEvent(SelectionKey key) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
try {
SocketChannel _channel = channel.accept();
_channel.configureBlocking(false);
_channel.register(_selector, SelectionKey.OP_READ);
_buffer.clear();
_buffer.put("Hi!\r\n".getBytes());
_buffer.flip();
_channel.write(_buffer);
} catch (IOException e) {
// nothing to do
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment