1

EventSource的理解与使用

 1 year ago
source link: https://www.fly63.com/article/detial/12448
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

EventSource是一个用于接收服务器推送事件的网络接口。它可以创建一个持久的连接到一个HTTP服务器,从而实时地获取服务器发送的text/event-stream格式的事件。这种方式可以实现客户端和服务器之间的单向通信,适合于处理一些不需要客户端发送数据的场景,例如社交媒体状态更新、新闻推送或者将数据存储到客户端的数据库等。

EventSource使用

EventSource的使用方法很简单,只需要创建一个EventSource对象,并传入一个URL作为参数,就可以监听服务器发送的事件了。例如:

// 创建一个EventSource对象
var source = new EventSource('sse.php');

// 监听message事件,该事件是默认的无名事件
source.addEventListener('message', function(e) {
  // e.data是服务器发送的数据
  console.log(e.data);
}, false);

// 监听open事件,该事件表示连接已经建立
source.addEventListener('open', function(e) {
  // 连接成功
  console.log("Connected");
}, false);

// 监听error事件,该事件表示连接出错或者关闭
source.addEventListener('error', function(e) {
  if (e.readyState == EventSource.CLOSED) {
    // 连接关闭
    console.log("Disconnected");
  }
}, false);

// 关闭连接
source.close();

EventSource对象

EventSource对象还有一些属性和方法可以使用,例如:

  • readyState:表示连接的状态,可能的值有CONNECTING ( 0 ),OPEN ( 1 ),或者CLOSED ( 2 )。
  • url:表示源的URL。
  • withCredentials:表示是否使用跨域(CORS)凭证。
  • close():关闭连接,并将readyState设置为CLOSED。

除了默认的message事件之外,服务器还可以发送带有event字段的事件,这样就可以触发自定义的事件了。例如:

// 服务器端发送如下数据:
// data: Hello
// event: greeting

// 客户端监听greeting事件
source.addEventListener('greeting', function(e) {
  // e.data是Hello
  console.log(e.data);
}, false);

EventSource是一种简单而有效的实现服务器推送事件的方式,它可以让客户端实时地获取服务器的更新,提高用户体验和效率。不过它也有一些局限性,例如:

  • 它只支持文本格式的数据,不能发送二进制数据。
  • 它只能实现单向通信,不能让客户端向服务器发送数据。
  • 它在不使用HTTP/2的情况下,会受到浏览器对最大打开连接数的限制。

因此,在选择使用EventSource时,需要根据具体的需求和场景进行权衡和评估。

链接: https://www.fly63.com/article/detial/12448


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK