我正在尝试设计一个聊天应用程序,在其中我试图通过Pusher的专用通道传递消息以进行实时传递。

我正在使用Smart Admin Theme's ajax version,并且正在使用主题本身附带的聊天UI插件。

基本上,我有Mapbox地图,并使用Leaflet在地图上放置了很多标记,每个标记都是用户。

因此,基本上,当用户登录时,他可以查看地图上的其他用户,并且当他单击地图时,将执行以下代码:

// Binding the marker on click event to bring up the chat
marker.on('click', function(){
    var chatboxId = 'private-' + currentUser.id + '-' + user.id;
    chatboxManager.addBox(chatboxId, {
        first_name: user.first_name,
        last_name: user.last_name,
    });

    // Creating a new chatbox
    $('#' + chatboxId).chatbox({
        messageSent: function(id, user, message){
            this.boxManager.addMsg('Me', message);

            splittedId = id.split('-');

            $.ajax({
                url: '/messages',
                method: 'post',
                type: 'json',
                data: {
                    receiver_id: splittedId[2],
                    body: message
                }
            });
        }
    });

    // Initializing pusher and authenticating the private channel
    var pusher = new Pusher('082bab423e2a8be3da2a', {
        authTransport: 'jsonp',
        authEndpoint: '/pusher/auth'
    });

    // Subscribing to the channel where the name of the channel is private-senderId-receiverId
    var chat = pusher.subscribe('private-' + user.id + '-'  + currentUser.id);
    console.log(chat);
    chat.bind('message', function(response){
        console.log(response);
    });
});


此代码为在地图上单击的用户生成一个新的聊天框。此时,pusher也已初始化,它与“ / pusher / auth”联系以进行专用通道的身份验证。

身份验证工作正常。我知道这是因为pusher返回的令牌应该与JSON中的令牌相同。然后,我将channel变量绑定为侦听“ message”事件,但无法侦听该信道上的新消息。

另外,当我尝试console.log(chat)(专用通道)时,它将在控制台中输出:


Object { callbacks: Object, global_callbacks: Array[0], failThrough:
b/<(), name: "private-1-1", pusher: Object, subscribed: false }



由于某种原因,订阅者为假。我究竟做错了什么?我确定我在某处缺少小东西,而我已经在这里待了两个多小时了。有人可以指出我在想什么吗?

编辑:服务器端路由进行身份验证

Route::get('/pusher/auth', function(\Illuminate\Http\Request $request, \App\User $user){
    $data = $request->all();

    $explodedChannel = explode('-' ,$data['channel_name']);

    if($user->currentUser()->id == $explodedChannel[2]){
        $pusher = new \Pusher(
            getenv('PUSHER_PUBLIC'),
            getenv('PUSHER_PRIVATE'),
            getenv('PUSHER_APPID')
        );
        echo $pusher->socket_auth($data['channel_name'], $data['socket_id']);
    }
    else{
        return response()->json('Forbidden', 403);
    }
});

最佳答案

编辑服务器端代码,其中echo auth响应如下:

编辑这个

 echo $pusher->socket_auth($data['channel_name'], $data['socket_id']);




        $auth= $pusher->socket_auth(Input::get('channel_name'), Input::get('socket_id'));
        $callback = str_replace('\\', '', $_GET['callback']);
        header('Content-Type: application/javascript');
        echo($callback . '(' . $auth . ');');
        return;

关于javascript - 无法听推杆私有(private) channel 事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30870937/

10-11 06:01