美文网首页node
HTML5—EventSource服务端推送事件

HTML5—EventSource服务端推送事件

作者: 幸福镰刀 | 来源:发表于2016-12-27 20:35 被阅读0次

    初始化事件源,指定一个接受事件的URL:

    var evtSource = new EventSource("/sendMessage");
    

    监听消息:

    //收到服务器发生的事件时触发
    evtSource.onmessage = function (e) {
        console.log(e.data);
    }
    //成功与服务器发生连接时触发
    evtSource.onopen = function () {
        console.log("Server open")
    } 
    //出现错误时触发
    evtSource.onerror = function () {
        console.log("Error")
    } 
    
     //自定义事件
    evtSource.addEventListener("myEvent", function (e) {
        console.log(e.data);
    }, false)
    

    服务器端nodejs实现:

    • 把报头 "Content-Type" 设置为 "text/event-stream"
    • 字段:每个事件之间通过空行来分隔

    字段为空白,表示该行是注释,会在处理时被忽略。
    event: 表示该行用来声明事件的类型。浏览器在收到数据时,会产生对应类型的事件。
    data: 消息的数据字段。如果该条消息包含多个data字段,则客户端会用换行符把它们连接成一个字符串来作为字段值。
    id: 事件ID,会成为当前EventSource对象的内部属性"最后一个事件ID"的属性值。
    retry: 一个整数值,指定了重新连接的时间(单位为毫秒),如果该字段值不是整数,则会被忽略.

    var http = require('http');
    var fs = require('fs');
    
    http.createServer(function (req, res) {
        if(req.url === '/sendMessage') {
            res.writeHead(200, {
                "Content-Type": "text/event-stream" //设置头信息
            });
    
            setInterval(function () {
                res.write(
                    //事件一
                    "data:" + new Date().toLocaleTimeString() + "\n\n" + //必须“\n\n”结尾
                    //事件二
                    ": '这是注释!'" + "\n" +
                    "event: myEvent" + "\n" + 
                    "data:" + new Date().toLocaleString() + "\n\n"
                );
            }, 1000);
        } else {
            fs.readFile('./index.html', function (err, content) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.end(content, 'utf-8');
            });
        }
    
    }).listen(3000);
    

    相关文章

      网友评论

        本文标题:HTML5—EventSource服务端推送事件

        本文链接:https://www.haomeiwen.com/subject/duolvttx.html