srv.js:
const sep='\r\n' const html=`<div id="log"></div><script> const xhr=new XMLHttpRequest xhr.open('POST', '/msg', 1) xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") let cur=0, sep=${JSON.stringify(sep)} xhr.withCredentials=!0 xhr.onreadystatechange=_=>{ if(xhr.readyState<3) return; const xr=xhr.response for(;;) { const xr1=xr.substr(cur, xr.length) const n=xr1.indexOf(sep) if(n<0) break const data=xr1.substr(0, n) cur+=n+sep.length if(data.match(/^-+$/)) continue log.innerHTML+="<div>### "+data+"</div>" } } xhr.send() </script>` require('http').createServer(async (req, res)=>{ if(!req.url.match(/\/msg/)) return res.end(html) res.write('-'.repeat(1024)+sep) for(let i=0; i<6; i++) { res.write(`${i*11}`+sep) await new Promise(r=>setTimeout(r, 1000)) } res.end('--end--'+sep) }).listen(7777)
运行:
node srv
打开浏览器 http://127.0.0.1:7777/ ,每隔一秒从服务器接收一行数据,最终效果效果如下:
### 0 ### 11 ### 22 ### 33 ### 44 ### 55 ### --end--
相关文档
暂无
随便看看
畅言模块加载中