Skip to content

Instantly share code, notes, and snippets.

@liweinan
Created July 13, 2017 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save liweinan/999d1e48036a03c68ca22c5190c2a0af to your computer and use it in GitHub Desktop.
Save liweinan/999d1e48036a03c68ca22c5190c2a0af to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* Created by weinanli on 13/07/2017.
*/
public class BasicNIOUsage {
public static void main(String[] args) throws Exception {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (!Thread.interrupted()) {
selector.select();
Set selectedKeys = selector.selectedKeys();
Iterator iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) (iterator.next());
if (key.isAcceptable()) {
dispatchAccept(key);
}
iterator.remove();
}
}
}
static void dispatchAccept(SelectionKey key) {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
try {
System.out.println("Client request accepted");
serverSocketChannel.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment