【问题标题】:Laravel 5.7 - Broadcasting - socket.io - redis : Nothing happen on clientLaravel 5.7 - 广播 - socket.io - redis:客户端没有任何反应
【发布时间】:2018-08-29 19:20:04
【问题描述】:

几天以来,我阅读了有关如何在本地计算机上设置 laravel-echo 的信息。我设法能够使用 redis 和 socket.io 运行 laravel-echo-server。

问题是事件被触发了,但客户端什么也没发生。

我知道该事件已被触发,因为它已登录到我的 Horizo​​n.log 文件中。

Horizon started successfully.
[2018-08-29 18:35:30][31] Processing: App\Events\NewModel
[2018-08-29 18:35:31][31] Processed:  App\Events\NewModel

然后,在我的 echo.log 文件中,我可以看到用户已连接到通道并 echo 触发了事件。

L A R A V E L  E C H O  S E R V E R

version 1.3.9

⚠ Starting server in DEV mode...

✔  Running at localhost on port 60010
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

[6:35:15 PM] - QW3VITRzWPH4FvxPAAAB joined channel: channel-name
Channel: presence-channel-name
Event: App\Events\NewModel

它运行在 60010 端口,因为当我尝试在 6001 端口上运行时,客户端无法连接。

我在 Windows 10 机器上使用 virtualbox/homestead。

有端口转发到我的 Homestead.yaml

ports:
    - send: 60010
      to: 6001

所以,我不明白为什么客户端不记录事件。这就是为什么我现在的代码

回声.js
/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from "laravel-echo"
window.io = require('socket.io-client');
// Have this in case you stop running your laravel echo server
if (typeof io !== 'undefined') {
  window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':60010',
  });
    console.log('Connected to socket.io');
} else {
    console.log('Not connected to socket.io');
}

window.Echo.channel('channel-name')
    .listen('NewModel', (e) => {
        console.log('1:');
        console.log(e);
    })
    .listen('App\Events\NewModel', (e) => {
        console.log('2:');
        console.log(e);
    })
    .listen('App.Events.NewModel', (e) => {
        console.log('3:');
        console.log(e);
    });
laravel-echo-server.json
{
    "authHost": "https://app.torque.homestead",
    "authEndpoint": "/broadcasting/auth",
    "clients": [{
        "appId": "appId",
        "key": "key"
    }],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "127.0.0.1"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "",
    "port": "60010",
    "protocol": "https",
    "socketio": {},
    "sslCertPath": "app.torque.homestead.crt",
    "sslKeyPath": "app.torque.homestead.key",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}
频道.php
<?php

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/


Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('channel-name', function () {
    return true;
});

如果您想查看其他文件,请告诉我。其实我不知道需要什么来解决这个问题。

我认为问题可能来自转发端口...但就像我说的,使用 6001 不起作用。

我尝试了很多东西,比如更改端口(可能不是正确的组合,比如 60010 上的客户端和 6001 上的服务器????)

我也多次将该行更改为 echo.js

host: window.location.hostname + ':60010',

我正在使用一些版本:

vagrant@homestead:~$ node -v
v10.8.0
vagrant@homestead:~$ npm -v
6.4.0
vagrant@homestead:~$ php -v
PHP 7.2.9-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Aug 19 2018 07:16:54) ( NTS )

packages.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "babel-preset-react": "^6.24.1",
        "bootstrap": "^4.1.3",
        "cross-env": "^5.2.0",
        "jquery": "^3.2",
        "laravel-mix": "^2.1.14",
        "lodash": "^4.17.4",
        "popper.js": "^1.14.4",
        "vue": "^2.5.17"
    },
    "dependencies": {
        "@fortawesome/fontawesome": "^1.1.8",
        "@fortawesome/fontawesome-free-brands": "^5.0.13",
        "@fortawesome/fontawesome-free-regular": "^5.0.13",
        "@fortawesome/fontawesome-free-solid": "^5.0.13",
        "@fortawesome/fontawesome-free-webfonts": "^1.0.9",
        "@fortawesome/vue-fontawesome": "0.0.22",
        "ajv": "^6.5.3",
        "bootstrap-confirmation2": "^4.0.1",
        "datatables.net": "^1.10.19",
        "datatables.net-bs4": "^1.10.19",
        "datatables.net-buttons": "^1.5.3",
        "datatables.net-buttons-bs4": "^1.5.3",
        "express": "^4.16.3",
        "ioredis": "^4.0.0",
        "laravel-echo": "^1.4.0",
        "laravel-echo-server": "^1.3.9",
        "socket.io": "^2.1.1",
        "socket.io-client": "^2.1.1",
        "vee-validate": "^2.0.9",
        "vue-inject": "^2.1.1",
        "yarn": "^1.9.4"
    }
}

composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": "^7.1.3",
        "aloha/twilio": "^4.0",
        "eyewitness/eye": "dev-beta",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "^6.3",
        "laravel/framework": "5.7.*",
        "laravel/horizon": "^1.3",
        "laravel/passport": "^6.0",
        "laravel/tinker": "^1.0",
        "predis/predis": "^1.1"
    },
    "require-dev": {
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

谢谢你帮助我!

--编辑--

在 mcklayin 建议我之后,我寻找 redis 数据。所以我运行这个:

vagrant@homestead:/var/lib$ redis-cli --scan
presence-channel-name:members
horizon:1
horizon:34
horizon:supervisors
horizon:measured_jobs
horizon:9
horizon:monitor:time-to-clear
horizon:job:App\Jobs\ProcessModels
horizon:35
horizon:queue:default
horizon:job_id
horizon:job:App\Events\NewModel
horizon:masters
horizon:last_snapshot_at
horizon:33
horizon:master:homestead-xVse
horizon:failed_jobs
horizon:32
horizon:supervisor:homestead-xVse:supervisor-1
horizon:recent_jobs
horizon:measured_queues

--编辑 2--

有 App\Events\NewModel.php 文件

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewModel implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }

    public function broadcastAs()
    {
        return 'NewModel';
    }
}

【问题讨论】:

  • 客户端连接socket成功了吗?
  • 我认为...在 echo.log 我可以看到这个[6:35:15 PM] - QW3VITRzWPH4FvxPAAAB joined channel: channel-name。这来自主管我的 laravel-echo.conf 文件句柄。据说客户端加入频道,客户端控制台从 echo.js 文件中收到此消息Connected to socket.io
  • 你的 QUEUE_DRIVER 是什么?如果你使用redis,我认为你的广播可以在队列中
  • 我的广播和队列都设置为 redis BROADCAST_DRIVER=redis QUEUE_DRIVER=redis --- 我只是看看我的配置文件,它被设置为使用 .env 变量。
  • 查看redis数据

标签: php laravel-5 redis socket.io laravel-echo


【解决方案1】:

尝试将,添加到 App\Events\NewModel:

public function broadcastAs()
    
{
        
    return 'NewModel';
    
}

并在客户端的事件名称前添加点符号:

window.Echo.channel('channel-name')
    .listen('.NewModel', (e) => {
        console.log('1:');
        console.log(e);
    })

【讨论】:

  • 我只是按照你的建议做了。 echo.log 和 Horizo​​n.log 显示事件已处理,但客户端没有任何反应。
  • 尝试将 window.Echo.channel('channel-name') 更改为 window.Echo.private('channel-name')
  • 我刚刚做了,将 shouldBroadcastOn() 更改为 PrivateChannel('channel-name') 到 NewModel.php 中,结果仍然相同。
  • 能否将 NewModel.php 添加到问题描述中?
  • 看看--EDIT 2--
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2018-01-09
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2012-02-22
  • 2018-06-26
相关资源
最近更新 更多