Use EventSource Achieve Comet

本文介绍 HTML5 中的 EventSource API,并通过一个实战示例展示了如何建立与服务器的持久连接来接收实时数据更新。文章包括客户端和服务端的具体实现细节。
部署运行你感兴趣的模型镜像

Firstly introduce the HTML5 API:

        The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling EventSource.close().

Usage:

var evtSource = new EventSource("/data");//向服务器接收数据

Event API:

//receive server info 
evtSource.onmessage = function (e) {
    console.log(e.data);
}
//trigger by connect server success 
evtSource.onopen = function () {
    console.log("Server open")
} 
//trigger by some err
evtSource.onerror = function () {
    console.log("Error")
} 

Example(Base on node):

        

var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
    if(req.url=='/'){
        fs.readFile("index.html",function(err,buf){
            if(err){
                res.end(404);return
            }else{
                res.end(buf);
            }
        });
    }else if(req.url=="/data"){
        res.setHeader('Cache-control', 'no-cache');
        res.setHeader('Content-Type', 'text/event-stream');
        let i=0;
        while(i<1000){
            console.log(i);
            res.write("data:" + new Date().toLocaleTimeString() + "\n\n" + 
            "data:" + i + "\n\n");//这里必须为\n\n才能是数据流分开,同时事件流给前台只会是data属性,不能设置其他属性

             i++;
        }
        
    }
}).listen(3000)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    
    var evtSource = new EventSource('/data');
    //收到服务器发生的事件时触发
        evtSource.onmessage = function (e) {
        console.log(e.data);
    }
    //成功与服务器发生连接时触发
        evtSource.onopen = function () {
            console.log("Server open")
    } 
    //出现错误时触发
    evtSource.onerror = function () {
        console.log("Error")
        } 
</script>
</html>

     AS follow result is:

        

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值