Created
November 26, 2013 03:46
-
-
Save kylefeng/7653176 to your computer and use it in GitHub Desktop.
NIO Echo Server Demo
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.net.ServerSocket; | |
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 PlainNioEchoServer { | |
public void server(int port) throws IOException { | |
System.out.println("Listening for connections on port " + port); | |
ServerSocketChannel serverChannel = ServerSocketChannel.open(); | |
ServerSocket ss = serverChannel.socket(); | |
InetSocketAddress addr = new InetSocketAddress(port); | |
ss.bind(addr); | |
serverChannel.configureBlocking(false); | |
Selector selector = Selector.open(); | |
serverChannel.register(selector, SelectionKey.OP_ACCEPT); | |
while (true) { | |
selector.select(); | |
Set<SelectionKey> readyKeys = selector.selectedKeys(); | |
Iterator<SelectionKey> iterator = readyKeys.iterator(); | |
while (iterator.hasNext()) { | |
SelectionKey key = iterator.next(); | |
iterator.remove(); | |
if (key.isAcceptable()) { | |
ServerSocketChannel server = (ServerSocketChannel) key.channel(); | |
SocketChannel client = server.accept(); | |
System.out.println("Accepted connection from " + client); | |
client.configureBlocking(false); | |
client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, | |
ByteBuffer.allocate(100)); | |
} | |
if (key.isReadable()) { | |
SocketChannel client = (SocketChannel) key.channel(); | |
ByteBuffer output = (ByteBuffer) key.attachment(); | |
client.read(output); | |
} | |
if (key.isWritable()) { | |
SocketChannel client = (SocketChannel) key.channel(); | |
ByteBuffer output = (ByteBuffer) key.attachment(); | |
output.flip(); | |
client.write(output); | |
output.compact(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
new PlainNioEchoServer().server(9999); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment