!7 import java.nio.*; import java.nio.channels.*; static long timeout = 30000+10000; // idle time + latency static ConnectedInstances cI; static ReliableSingleThread rst = new(r update); static int theNumber; static int port = 6000; static Set channels = synchroSet(); static Selector selector; sclass State { S computerID; int countSeen = -1; } p { cI = new ConnectedInstances; cI.connected2.onChange(rst); selector = Selector.open(); ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); InetSocketAddress sockAddr = new InetSocketAddress(port); serverChannel.socket().bind(sockAddr); serverChannel.register(selector, SelectionKey.OP_ACCEPT); thread "Server Accept Loop" { acceptLoop(); } } svoid acceptLoop { while licensed { // wait for events selector.select(); Iterator key = selector.selectedKeys().iterator(); while (key.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) continue; if (key.isAcceptable()) acceptOnSocket(key); else if (key.isReadable()) readFromSocket(key); } } } //accept a connection made to this channel's socket static void acceptOnSocket(SelectionKey key) throws IOException { ServerSocketChannel serverChannel = cast key.channel(); SocketChannel channel = serverChannel.accept(); channel.configureBlocking(false); Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); print("Connected to: " + remoteAddr); // register channel with selector for further IO //dataMapper.put(channel, new ArrayList()); channel.register(selector, SelectionKey.OP_READ); } static void readFromSocket(SelectionKey key) throws IOException { SocketChannel channel = cast key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int numRead = channel.read(buffer); if (numRead == -1) { //this.dataMapper.remove(channel); Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); print("Connection closed by client: " + remoteAddr); channel.close(); key.cancel(); ret; } print("Got data: " + new String(buffer.array(), 0, numRead)); } html { ret "Use port " + port; } /*svoid sendNumber(O ws) { State s = wsToState.get(ws); if (s != null && theNumber != s.countSeen) { s.countSeen = theNumber; print("Sending number to " + s.computerID + ": " + theNumber); call(ws, 'send, str(theNumber)); } }*/ svoid update { /* print("OS Instances update"); if (webSocketManager.isEmpty()) ret; int value = cI.value(); //if (value == theNumber) ret; theNumber = value; for (O ws : webSocketManager.webSockets()) pcall { sendNumber(ws); } print("OS Instances update done");*/ }