1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package debug.io.model.reactor.singlereactorsinglethread;
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;
public class Reactor implements Runnable {
ServerSocketChannel serverSocketChannel; Selector selector;
public Reactor(int port) { try { this.serverSocketChannel = ServerSocketChannel.open(); this.serverSocketChannel.configureBlocking(false); this.serverSocketChannel.bind(new InetSocketAddress(port)); this.selector = Selector.open(); this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT, new Acceptor(this.serverSocketChannel, this.selector)); } catch (Exception ignored) { } }
@Override public void run() { while (true) { try { this.selector.select(); Set<SelectionKey> selectionKeys = this.selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); this.dispatch(sk); } } catch (Exception ignored) { } } }
private void dispatch(SelectionKey sk) { Runnable r = (Runnable) sk.attachment(); r.run(); } }
|