Laravel Echo Server 换为 Soketi
DEMO
Laravel
Composer
推送需要用到
composer require pusher/pusher-php-server
广播中间件
routes/api.php 添加
use Illuminate\Support\Facades\Broadcast;
Broadcast::routes(['middleware' => ['auth:sanctum']]);
广播配置
configs/broadcasting.php 修改为
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY', 'app-key'),
'secret' => env('PUSHER_APP_SECRET', 'app-secret'),
'app_id' => env('PUSHER_APP_ID', 'app-id'),
'options' => [
'host' => env('PUSHER_HOST', '127.0.0.1'),
'port' => env('PUSHER_PORT', 6001),
'scheme' => env('PUSHER_SCHEME', 'http'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
.env 配置
BROADCAST_DRIVER=pusher
# WebSocket
PUSHER_APP_KEY=app-key
PUSHER_APP_ID=app-id
PUSHER_APP_SECRET=app-secret
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
SOKETI_DEFAULT_APP_ENABLE_CLIENT_MESSAGES=true
KEY、ID 和 SECRET 自己改下
前端
yarn
yarn add pusher-js
yarn remove socket.io-client
配置
原本
window.io = require("socket.io-client");
window.Echo = new Echo({
broadcaster: "socket.io",
host: window.location.hostname + ":6001",
auth: {
headers: {
Authorization: localStorage.token,
},
},
});
改为
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
key: process.env.REACT_APP_PUSHER_APP_KEY,
wsHost: process.env.REACT_APP_PUSHER_HOST,
wsPort: process.env.REACT_APP_PUSHER_PORT,
wssPort: process.env.REACT_APP_PUSHER_PORT,
forceTLS: false,
encrypted: true,
disableStats: true,
enabledTransports: ["ws", "wss"],
authorizer: (channel, options) => {
return {
authorize: (socketId, callback) => {
axios
.post("/broadcasting/auth", {
socket_id: socketId,
channel_name: channel.name,
})
.then((response) => {
callback(false, response.data);
})
.catch((error) => {
callback(true, error);
});
},
};
},
});
.env
# WebSocket
REACT_APP_PUSHER_APP_KEY=app-key
REACT_APP_PUSHER_HOST=127.0.0.1
REACT_APP_PUSHER_PORT=6001
感谢
博客:Soketi WebSockets 无法使用客户端消息
本作品采用《CC 协议》,转载必须注明作者和本文链接
这个 Soketi 有什么优势吗 对比 workerman
就是连接不上,一直提示4001
我的是用 Docker 创建的,需要传值进去,应该还可以写
config.json
目前还没找到怎么传入。连接是正常了,日志出现以下错误,请帮忙看看吧?