我想触发一个事件来推送私有(private) channel ,我的服务器端语言是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
添加您的应用程序 key 、 channel 名称和事件名称之后我们需要在服务器端授权这是示例 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
最佳答案
对于在 Laravel 上通过 Pusher 使用 WebSockets,我建议使用 Laravel Echo 包作为 React 部分。在后端的 config/broadcasting.php 设置 Pusher 的配置。
有关如何在后端和前端使用 Pusher,请参阅官方文档 Laravel 的更多详细信息。
https://laravel.com/docs/8.x/broadcasting#pusher-channels
关于reactjs - 在 react 应用程序中触发私有(private) channel 的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54984812/