Skip to content

Instantly share code, notes, and snippets.

@MaZderMind
Created April 21, 2019 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaZderMind/12fe3b370e654f31ea22aaa540f5a741 to your computer and use it in GitHub Desktop.
Save MaZderMind/12fe3b370e654f31ea22aaa540f5a741 to your computer and use it in GitHub Desktop.
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

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