服务器发送事件(SSE):如何广播消息? [英] server sent event (SSE) : how to broadcast a message?

查看:95
本文介绍了服务器发送事件(SSE):如何广播消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是:

$.post('events.php', {'message': 'hello world'}, function(res) {
 
});

  • user1 向服务器发送消息(一个简单的 POST 请求)
  • 服务器将该消息广播给所有订阅了 EventSource 的用户
  • 服务器部分是 (events.php)

    Server part is (events.php)

    <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
    
    function sendMsg($id, $msg) {
        echo "id: $id" . PHP_EOL;
        echo "data: $msg" . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }
    
    while(true) {
        $serverTime = time();
        if (isset($_POST['message'])) {
            sendMsg($serverTime, 'message: ' . date("h:i:s", time()));
            sleep(5);
        }
    }
    

    我尝试了无限循环 while(true) 以避免 3 秒轮询.我也试过没有那个无限循环.只有发送消息的用户才能收到事件.

    I tried that infinite loop while(true) to avoid that 3 seconds polling. I also tried without that infinite loop. Only the user who sends the message receives the event.

    我知道这种方法不好.但是,将 SSE 用于聊天应用程序的最佳做法是什么?

    I understand that approach is not good. But what would be the good practice to use SSE for a chat application ?

    如何向所有用户发送事件?

    How can I send events to ALL users ?

    推荐答案

    SSE 是每个客户端的专用套接字和专用进程.

    SSE is a dedicated socket and dedicated process per client.

    这意味着您的服务器端进程与浏览器客户端具有基本相同的选择:轮询或订阅.

    That means your server-side process has basically the same choices as the browser clients: poll or subscribe.

    因为您的数据库可能与 SSE 服务器进程位于同一服务器/LAN 上,所以重复轮询没有与浏览器客户端相同的缺点.因此,要开发聊天应用程序,您可以定期轮询存储聊天消息的 SQL 数据库,以查看是否有新消息.

    Because your database is likely to be on the same server/LAN as the SSE server process, repeated polling doesn't have the same downsides it does for a browser client. So to do a chat application you could regularly poll a SQL database, that stores chat messages, to see if anything new has arrived.

    subscribe 方法的一个例子是让每个 SSE 进程打开一个连接到本地运行的聊天服务器的专用套接字,每次有新聊天消息时,该套接字将广播给每个 SSE 侦听器到货了.

    An example of the subscribe approach would be to have each SSE process open a dedicated socket to a chat server, running locally, which will broadcast to each of those SSE listeners each time a new chat message arrives.

    这篇关于服务器发送事件(SSE):如何广播消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆