-
-
Save superalsrk/0d755571982f7e35e864636731b14171 to your computer and use it in GitHub Desktop.
This file contains 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
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