Skip to content

Instantly share code, notes, and snippets.

@andriika
Last active June 19, 2018 03:50
Show Gist options
  • Save andriika/0b29fd712f67388742649ed06407f7ba to your computer and use it in GitHub Desktop.
Save andriika/0b29fd712f67388742649ed06407f7ba to your computer and use it in GitHub Desktop.
single-threaded server based on Java NIO selector
package acme;
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;
public class NioSelectorServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress("localhost", 5454));
server.configureBlocking(false);
Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(256);
while (true) {
selector.select();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
if (key.isAcceptable()) {
SocketChannel client = server.accept();
register(selector, client);
}
if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
processRequest(buffer, client);
}
keys.remove();
}
}
}
private static void processRequest(ByteBuffer buffer, SocketChannel client) throws IOException {
client.read(buffer);
if (new String(buffer.array()).trim().equals("EXIT")) {
client.close();
}
buffer.flip();
client.write(buffer);
buffer.clear();
}
private static void register(Selector selector, SocketChannel client) throws IOException {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment