我是否正确使用了 websockets?

Am I using websockets correctly?

背景:

我是如何使用它的

我正在制作一个由单个用户控制的幻灯片。如果我希望那个人为该页面上的所有人更改幻灯片,那么我会使用用户移动到的幻灯片编号进行 AJAX 调用。

$('#nextCard').click(function(){
    if ($('#card-' + (cardId + 1)).length != 0) {  // if there is a next card
        $('#card-' + (cardId)).hide();             // hide current card
        cardId++;                                  // increment the card id
        $('#card-' + (cardId)).show();             // and show the next card
        location.hash = cardId;

        /**
         * make ajax call to push function
         */
        $.ajax({
            method: 'post',
            url: '<?php echo base_url('learn/pusher'); ?>',
            data: {card_id: cardId},
            dataType: 'json',
            async: false,
        });
    }
});

此号码通过 ajax 发送到服务器,并通过推送器传送。

Pusher 然后将幻灯片编号实时发送给同一页面上的所有用户...实际上 推送 更改为不同的人的屏幕。​​

var channel = pusher.subscribe('notifications');
channel.bind('new-notification', function(data) {

    // call something here

});

然后数据推送时调用的函数会影响更改。

我的问题

我的印象是 Websockets 是 alternative/replacement 到 AJAX 和其他类似技术......但在这里我发现自己依赖 AJAX 将我的 Websockets 数据发送到来自服务器端的推送器。

我认为 Websockets 优于 AJAX 因为它更快,但在这里我发现自己被 AJAX 瓶颈了。

那么我在这里正确使用了 websockets 吗?

使用 AJAX 向您的服务器发送请求,然后触发 Pusher 事件以将其广播给订阅者是使用 Pusher 的一种惯用方式。底层 WebSockets 技术是双向的(更多信息 here),但 Pusher 的 pub/sub 模型是单向的。

您的用例的另一种选择是使用 client events。这允许您直接从客户端触发事件。这样做的额外考虑是您必须使用私人或在线频道。