Skip to content

Instantly share code, notes, and snippets.

@zhoulifu
Created November 17, 2016 09:29
Show Gist options
  • Save zhoulifu/0274f82f80347f7a02c238936efc55f5 to your computer and use it in GitHub Desktop.
Save zhoulifu/0274f82f80347f7a02c238936efc55f5 to your computer and use it in GitHub Desktop.
NIO DiscardServer
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.Set;
class Server implements Runnable {
private int port;
private final Selector selector;
private final ServerSocketChannel serverChannel;
Server(int port) throws IOException {
this.port = port;
selector = Selector.open();
serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
SelectionKey selectionKey = serverChannel.bind(new InetSocketAddress(port)).register(
selector, SelectionKey.OP_ACCEPT);
selectionKey.attach(new Acceptor());
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey key : selectedKeys) {
dispatch(key);
}
selectedKeys.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void dispatch(SelectionKey key) {
Runnable r = (Runnable) key.attachment();
if (r != null) {
r.run();
}
}
private class Acceptor implements Runnable{
@Override
public void run() {
try {
SocketChannel channel = serverChannel.accept();
if (channel != null) {
new Handler(selector, channel);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Handler implements Runnable{
private SocketChannel channel;
private SelectionKey selectionKey;
private ByteBuffer in = ByteBuffer.allocate(2048);
Handler(Selector selector, SocketChannel channel) throws IOException {
this.channel = channel;
channel.configureBlocking(false);
selectionKey = channel.register(selector, SelectionKey.OP_READ);
selectionKey.attach(this);
selector.wakeup();
}
@Override
public void run() {
byte[] bytes = new byte[1024];
int len;
try {
channel.read(in);
in.flip();
while ((len = in.remaining()) > 0) {
in.get(bytes, 0, Math.min(len, 1024));
System.out.print("received: " + new String(bytes));
}
in.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class DiscardServer {
private static Thread thread;
public static void main(String[] args) throws IOException, InterruptedException {
int port;
if (args.length == 1) {
port = Integer.valueOf(args[0]);
} else {
port = 8888;
}
thread = new Thread(new Server(port));
thread.start();
thread.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment