【EventSource】一种新的实时通信推送机制

147 阅读1分钟

EventSource

概念

  • EventSource是浏览器提供的一种新的实时通信推送机制。
  • EventSource实例会对HTTP 务器开启一个持久化的连接。

优势

  • 长连接,服务端可直接与客户端频繁通信,不再需要建立新的http请求
  • 自动重连机制,异常捕获
  • 实现简单,轻量级,安全可靠

缺点

  • 单向传输(服务端到客户端),不支持双向通信
  • 兼容性,部分浏览器版本不支持
  • 不支持二进制数据传输

语法

eventSource = new EventSource(url, configuration);
  • url: 资源路径
  • configuration(可选): withCredentials,默认为 false,指示 CORS 是否应包含凭据

API

事件

  • message: 接收消息
  • open: 通道正常
  • error: 连接错误

断开连接

EventSource.close()

示例

JS代码

        window.onload = function () {
            const evSource = new EventSource("http://localhost:9999/eventSource");
            const evnetList = document.querySelector("ul");
            evSource.onopen = (e) => {
                const newElement = document.createElement("li");
                newElement.textContent = `open:${e}`;
                evnetList.appendChild(newElement);
                setTimeout(()=>{
                    evSource.close();//关闭连接
                },10000)
            }
            evSource.onerror=(e)=>{
                const newElement = document.createElement("li");
                newElement.textContent = `error:${e}`;
                evnetList.appendChild(newElement);
            }
            evSource.onmessage = (e) => {
                const newElement = document.createElement("li");
                newElement.textContent = `message:${e.data}`;
                evnetList.appendChild(newElement);
            }
        }

Node服务器

服务端需要设置header的"Content-Type"为'text/event-stream'

app.get("/eventSource", (request, response) => {
    response.header("Content-Type", 'text/event-stream');
    response.header("Cache-Control", 'no-cache');
    interval = setInterval(function () {
        response.write("data:"+new Date()+"\n\n");
    }, 3000);
});

const server = app.listen(9999, () => {
    const host = server.address().address;
    const port = server.address().port;
});

页面呈现

image.png