猿人旅程

SSE(Server-Send Event) 服务器推送数据的

2018-04-09  本文已影响2人  Junting

Web API 接口: EventSource

EventSource 接口用于接收服务器发送的事件。它通过HTTP连接到一个服务器,以text/event-stream 格式接收事件, 不关闭连接。

服务端代码

<?php
# 指定数据类型,指定允许域访问
header("Content-Type: test/event-stream; charset=utf-8");
header("Access-Control-Allow-Origin:http://127.0.0.1");
echo "data: 现在北京时间是:".date('H:i:s')."\r\n\r\n";
?>

前端代码

let source;

function init(arg) {
  source = new EventSource('http://127.0.0.1/sse/data.php');
  source.onopen = () => {
    console.log("连接已建立", this.readyState);
  }
  source.onmessage = (event) => {
    console.log("从服务器拉取的时间:", event.data);
  }

  source.onerror = () => {
    console.log('');
  }
}
init();
上一篇下一篇

猜你喜欢

热点阅读