首页 > Web开发 > 详细

[go]websocket

时间:2020-01-18 15:24:54      阅读:69      评论:0      收藏:0      [点我收藏+]
  • http的特点
  1. 半双工: 同一个时刻,只能单向传数据(request/response).
  2. 服务器不能主动给客户端推消息

技术分享图片

  • 轮询(polling)
    不断的建立http连接,严重浪费了服务器端和客户端的资源. 人越多,服务器压力越大.
- server.js

let express = require('express');
let app = express();
app.use(express.static(__dirname));

app.get("/clock", function (req, res) {
    res.end(new Date().toLocaleTimeString());
});
app.listen(8080);
- client

<body>
<div id="clock"></div>
<script>
    setInterval(function () {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8080/clock', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                document.querySelector('#clock').innerHTML = xhr.responseText;
            }
        };
        xhr.send();
    }, 1000);
</script>
</body>

- 访问http://localhost:8080/clock
  • 长轮询(long polling)(comet)
    当一次请求完成后, 在发起进行下一次
    技术分享图片
- client


<body>
<div id="clock"></div>
<script>
    setInterval(function () {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8080/clock', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                document.querySelector('#clock').innerHTML = xhr.responseText;
            }
        };
        xhr.send();
    }, 1000);
</script>
</body>
- server.js


let express = require('express');
let app = express();
app.use(express.static(__dirname));

app.get("/clock", function (req, res) {
    //优化: 当时间为每隔5的倍数才返回.
    let $timer = setInterval(function () {
        let date = new Date();
        let seconds = date.getSeconds();
        if (seconds % 5 === 0) {
            res.end(new Date().toLocaleTimeString());
            clearInterval($timer)
        }
    }, 1000);

});
app.listen(8080);

[go]websocket

原文:https://www.cnblogs.com/iiiiiher/p/12209115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!