!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(); sclass State { S computerID; int countSeen = -1; } p { cI = new ConnectedInstances; cI.connected2.onChange(rst); InetSocketAddress sockAddr = new InetSocketAddress(port); AsynchronousServerSocketChannel serverSock = AsynchronousServerSocketChannel.open().bind(sockAddr); //start to accept the connection from client serverSock.accept(serverSock, new CompletionHandler() { public void completed(AsynchronousSocketChannel sockChannel, AsynchronousServerSocketChannel serverSock) { //a connection is accepted, start to accept next connection serverSock.accept(serverSock, this); channels.add(channel); //start to read message from the client startRead( sockChannel ); } public void failed(Throwable exc, AsynchronousServerSocketChannel serverSock) { print("fail to accept a connection"); } }); } static void startRead( AsynchronousSocketChannel sockChannel) { final ByteBuffer buf = ByteBuffer.allocate(2048); //read message from client sockChannel.read(buf, sockChannel, new CompletionHandler() { @Override public void completed(Int result, AsynchronousSocketChannel channel) { buf.flip(); // echo the message startWrite(channel, buf); // start to read next message again startRead(channel); } @Override public void failed(Throwable exc, AsynchronousSocketChannel channel) { print( "fail to read message from client"); } }); } static void startWrite(AsynchronousSocketChannel sockChannel, final ByteBuffer buf) { sockChannel.write(buf, sockChannel, new CompletionHandler() { @Override public void completed(Int result, AsynchronousSocketChannel channel) { // finish to write message to client, nothing to do // (close socket?) } @Override public void failed(Throwable exc, AsynchronousSocketChannel channel) { print("Fail to write message to client"); } }); } 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"); }