6

实时通信 | pusher 如何使用私有频道(四) - Tinywan

 2 years ago
source link: https://www.cnblogs.com/tinywan/p/15854185.html
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.
neoserver,ios ssh client

当需要以某种方式限制对频道的访问时,应使用私有频道。 为了让用户订阅私人频道权限,必须获得授权。 当使用 private- 通道名称调用 subscribe 方法时,通过对可配置身份验证 url 的 HTTP 请求进行身份验证。

授权架构图

  • (1)实例化pusher
  • (2)通过pusher连接WebSocket
  • (3)pusher:connection_established(socket_id)每个socket_id是唯一的
  • (4)通过pusher订阅私有频道
  • (5)通过自动以接口进行身份授权,请求参数:channel_name、socket_id
  • (6)身份授权授权接口签名:JSON:{"auth":"key:signatrue"}
  • (7)触发客户端pusher频道回调

安装依赖包

composer require pusher/pusher-php-server

授权接口代码

/**
 * @desc: pusher auth
 */
public function pusherAuth(Request $request)
{
    $param = $request->post();
    if (!isset($param['channel_name']) || !isset($param['socket_id'])) {
        return 403;
    }
    $options = array(
        'cluster' => 'ap3',
        'useTLS' => true
    );
    $pusher = new Pusher(
        '108365f54d1d934e76781',
        '9cfbfd3b06290c427de62',
        '13394324',
        $options
    );

    $presenceData = array('name' => 'Tinywan');
    return $pusher->presenceAuth($param['channel_name'], $param['socket_id'], '1', $presenceData);
}

身份验证 url地址:http://127.0.0.1:8787/test/pusher-auth

客户端代码

private_channel_client.html

<!DOCTYPE html>
<head>
    <title>Private channels</title>
    <script src="https://js.pusher.com/7.0/pusher.min.js"></script>
    <script>
        // (1) 创建实例
        const pusher = new Pusher('108365f54d1d934e76781', {
            cluster: 'ap3',
            authEndpoint: 'http://127.0.0.1:8787/test/pusher-auth',
            // auth: { headers: { "X-CSRF-Token": "SOME_CSRF_TOKEN" } },
        });

        // (2) 订阅频道
        var uid = 1;
        var privateChannel = pusher.subscribe('private-user-' + uid);

        // (3) 绑定事件
        privateChannel.bind('private-event', function(data) {
            alert(JSON.stringify(data));
        });
    </script>
</head>
<body>
<h1>Private channels Test</h1>
</body>

服务端代码

private_channel_server.php

<?php
/**
 * @desc pusher server
 * @author Tinywan(ShaoBo Wan)
 * @date 2022/02/10 16:02
 */
require_once '../../vendor/autoload.php';

$options = array(
    'cluster' => 'ap3',
    'useTLS' => true
);
$pusher = new Pusher\Pusher(
    '108365f54d1d934e76718',
    '9cfbfd3b06290c427d1e6',
    '13394341',
    $options
);

$data['message'] = 'Hi Tinywan private 2022';
$pusher->trigger('private-user-1', 'private-event', $data);

授权接口响应信息

服务端推送消息

客户端接收消息截图


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK