Created
April 21, 2019 19:13
-
-
Save MaZderMind/12fe3b370e654f31ea22aaa540f5a741 to your computer and use it in GitHub Desktop.
Example of a Nonblokcing Socket-Server with java.nio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Follow-Up reading Line-by-Line: https://gist.github.com/MaZderMind/0be1dea275ea25b39dc753583d742851