Sever-Sent Events (SSE) server pushes a practical example to a Web client

concept

Sever-Sent Events (SSE) enables the server to actively push messages to the client

Features:

  • Based on HTTP protocol
  • Sending messages from the server to the client can only be sent in one direction
  • Only text messages are supported
  • When not used over HTTP/2, SSE is limited by the maximum number of connections (Chrome, Firefox max 6 connections per browser)

event stream format

The event stream is simply a stream of text data, and the text should be encoded in UTF-8 format.
Each message is followed by a blank line as a separator.

  • Example 1: The client will receive the event type myevent with the message xxxx\nyyyy

event: myevent
data: xxxx
data: yyyy

  • Example 2: The event type is not specified, the event type is message by default, and the message is zzzz

data: zzzz

  • Example 3: Beginning with a colon indicates a comment, which can be used to prevent the connection from timing out. The server can periodically send a message comment line to keep the connection going.

: this is just a annotation

Combat Demo

  • renderings

Server-Sents Events

  • web client
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>SSE Demo</title>
</head>
<body>
    <div id="messages"></div>
    <script>
        const source = new EventSource('sse.php');

        // 建立连接
        source.onopen = function () {
      
      
            var messages = document.getElementById('messages');
            messages.innerHTML += 'connection is established' + '<br>';
        };

        // ping 事件类型消息
        source.addEventListener("ping", function(event) {
      
      
            var messages = document.getElementById('messages');
            messages.innerHTML += 'ping: ' + event.data + '<br>';
        });

        // message 事件类型消息
        source.onmessage = function(event) {
      
      
            var messages = document.getElementById('messages');
            messages.innerHTML += event.data + '<br>';
        };

        // 连接错误
	    source.onerror = function (event) {
      
      
	        var messages = document.getElementById('messages');
	        var data = 'connection state: ' + eventSource.readyState + ', error: ' + event
            messages.innerHTML += data + '<br>';
	    };
    </script>
</body>
</html>
  • Server
<?php

// 禁用缓存
header("Cache-Control: no-cache");
// 指明 MIMI
header("Content-Type: text/event-stream");
// 使用持久连接
header('Connection: keep-alive');


while (true) {
    
    
  // 发送 ping 事件类型消息
  echo "event: ping\n";
  echo 'data: {"time": "' . date('Y-m-d H:i:s'). '"}';
  echo "\n\n";


  if (time() % 5 === 0) {
    
    
    // 未指定事件类型,默认为 message 事件类型
    echo 'data: This is a message at time ' . date('Y-m-d H:i:s') . "\n\n";
  }

  ob_end_flush();
  flush();
  sleep(1);
}

reference

  • https://developer.mozilla.org/zh-CN/docs/Web/API/Server-sent_events
  • https://zhuanlan.zhihu.com/p/444011262
  • https://github.red/talking-about-eventstream/

Guess you like

Origin blog.csdn.net/xchenhao/article/details/129555747