在React App中将事件触发到私人频道

时间:2019-03-04 14:00:00

标签: reactjs laravel react-native real-time pusher

我想触发一个推送器专用通道事件,而我的服务器端语言是laravel,我查看了很多资源,但是我没有找到涵盖服务器端和前端的全面方法,最后我得到了此解决方案 在第一步中:

 export const SendChat = () => {
    try {
        var pusher = new Pusher('YOUR_APP_KEY', {
            cluster: 'ap2',
            forceTLS: true,
            authTransport: 'jsonp',
            authEndpoint: `${baseUrl}pusher/auth`,
        });
        var channel = pusher.subscribe('private-channel');
        channel.bind('pusher:subscription_succeeded', function() {
            var triggered = channel.trigger('client-EVENT_NAME', { 'message': 'Hi ....' });
            console.log(triggered)
        });

    } catch (error) {
        console.error(error);
    }
}

并在某处命名

<Button onClick={this.props.SendChat}  waves='light' >Send</Button>

您必须在推送器帐户设置中启用客户端事件

login to your pusher account -> select the channel ->App Settings -> select Enable client events -> update

添加您的应用密钥,通道名称和事件名称,之后我们需要在服务器端进行授权,这是示例laravel代码,首先在web.php中添加此路由

Route::get('pusher/auth', 'PusherController@pusherAuth');

使PusherController.php像这样:

public function pusherAuth()
{
    $user = auth()->user();

    if ($user) {
        $pusher = new Pusher('auth_key', 'secret', 'app_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;
    }else {
        header('', true, 403);
        echo "Forbidden";
        return;
    }
}

测试它,您应该会看到类似的内容

 Pusher : State changed : connecting -> connected with new socket ID 3953.****556
Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"83045ed1350e63c912f5:328fb78165d01f7d6ef3bb6d4a30e07c9c0ad0283751fc2c34d484d4fd744be2","channel":"private-chat"}}
Pusher : Event sent : {"event":"client-MessageSent","data":{"message":"Hi ...."},"channel":"private-chat"}
true

0 个答案:

没有答案