Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a Nonblokcing Socket-Server with java.nio
package de.mazdermind;
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;
public class Main {
public static void main(String[] args) throws IOException {
String bind = "0.0.0.0";
int port = 9999;
System.out.println(String.format("Starting Server on %s:%d", bind, port));
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress(bind, port));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
//noinspection InfiniteLoopStatement
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
SocketChannel client = serverSocket.accept();
System.out.println(String.format("Incoming Connection from %s", client.getRemoteAddress()));
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
read(client);
}
iter.remove();
}
}
}
private static void read(SocketChannel client) throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int numBytesRead = client.read(byteBuffer);
System.out.println(String.format("read %d bytes to buffer", numBytesRead));
}
}
@MaZderMind
Copy link
Author

MaZderMind commented Apr 21, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment