websocketd 是一个很小的命令后工具,可以让你的命令行接口程序封装成可通过 WebSocket 进行访问。
例如这样一个命令行程序 count.sh:
#!/bin/bash for COUNT in $(seq 1 10); do echo $COUNT sleep 1 done
可通过如下命令进行封装:
$ websocketd --port=8080 ./count.sh
然后你可以创建一个网页来测试 count.html:
<!DOCTYPE html> <pre id="log"></pre> <script> // helper function: log message to screen function log(msg) { document.getElementById('log').textContent += msg + '\n'; } // setup websocket with callbacks var ws = new WebSocket('ws://localhost:8080/'); ws.onopen = function() { log('CONNECT'); }; ws.onclose = function() { log('DISCONNECT'); }; ws.onmessage = function(event) { log('MESSAGE: ' + event.data); }; </script>