| Paste number 88566: | java-nio-basic |
| Pasted by: | ossareh |
| When: | 3 months, 4 weeks ago |
| Share: | Tweet this! | http://paste.lisp.org/+1WC6 |
| Channel: | None |
| Paste contents: |
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.io.*;
public class Server {
private ServerSocketChannel server;
private Selector selector;
public static void main(String[] args) throws Exception {
Server s = new Server(args[0], Integer.valueOf(args[1]));
s.recvLoop();
}
public void recvLoop() throws Exception {
for (;;) {
System.out.println("About to select");
System.out.println(String.format("found %d elements", selector.select()));
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
//SelectionKey key = it.next();
//it.remove(); //required
keys.remove(key);
Socket s = ((ServerSocketChannel)key.channel()).accept().socket();
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("k, thx, bye");
out.close();
}
Thread.sleep(500);
}
}
public Server(String host, int port) throws Exception {
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(host, port));
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
}
}
This paste has no annotations.