私はで与えられ、チュートリアル、次のいhttps://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8bを。
私がインストールされlaravel-echo-server
、redis
、socket.io
、laravel-echo
。
これは、の設定です laravel-echo-server init
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
このjsのコードは、の一番下にあるapp.blade.php
すべてのページに含まれています
<script type="module">
import Echo from 'laravel-echo'
window.io = require('socket.io-client');window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
console.log(e);
});
</script>
私は、イベントを作成しphp artisan make:event ExampleEvent
、以下のように
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ExampleEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-event');
}
public function broadcastWith()
{
return [
'data' => 'Hi bro!'
];
}
}
そして、次のルート
Route::get('test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
});
私はまた、キューリスナーを開始しました
php artisan queue:listen --tries=1
私は、ページにアクセスするとtest-broadcast
、私はターミナルでこれを参照してください
しかし、ブラウザのショーの何のコンソールは、一方でconsole.log(e);
何かを返す必要があります。また、私はこれをしませんでした
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
alert('hi')
console.log(e);
});
しかし、何も警告されませんでした。何かがリスニングと間違っているようです。
前もって感謝します。
更新
I receive this error from console of browser when visiting login
or any page includes app.blade.php
Update
I updated the script codes as below
<script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="{{ asset('/js/app.js') }}"></script>
<script type="module">
import Echo from 'laravel-echo'
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('.ExampleEvent', (e) => {
console.log(e);
});
</script>
The console still report error
TypeError: Error resolving module specifier: laravel-echo
update
I run
npm run development -- --watch
and this is the result
cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch"
'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ 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 ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs\2020-03-05T14_59_30_604Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `npm run development -- --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs\2020-03-05T14_59_30_697Z-debug.log
Altogether this what is required:
- Default Laravel installation
- composer require predis/predis
- Installation of NPM modules (laravel-echo-server, socket.io & laravel-echo)
Set up Laravel Echo Server through console (mostly default settings, except for domain name):
{ "authHost": "http://echo", "authEndpoint": "/broadcasting/auth", "clients": [ { "appId": "fc3de97a1787ea04", "key": "ecf31edced85073f7dd77de1588db13b" } ], "database": "sqlite", "databaseConfig": { "redis": {}, "sqlite": { "databasePath": "/database/laravel-echo-server.sqlite" } }, "devMode": true, "host": null, "port": "6001", "protocol": "http", "socketio": {}, "secureOptions": 67108864, "sslCertPath": "", "sslKeyPath": "", "sslCertChainPath": "", "sslPassphrase": "", "subscribers": { "http": true, "redis": true }, "apiOriginAllow": { "allowCors": true, "allowOrigin": "http://echo:80", "allowMethods": "GET, POST", "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id" } }
Setup of Redis Server and connecting to it with Laravel broadcasting.php file
'default' => env('BROADCAST_DRIVER', 'redis')
or BROADCAST_DRIVER=redis in .env file
- Adding route in web.php
Route::get('/test-broadcast', function(){ broadcast(new \App\Events\ExampleEvent); return response('OK'); });
- Adding code in bootstrap.js:
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
ADDED
window.Echo.channel('MyChannel') .listen('.ExampleEvent', (e) => { console.log(e); });
- Running
npm run dev
to compile all Javascript modules - Running
laravel-echo-server start
to start Laravel Echo Server - Running
php artisan queue:listen --tries=1
to start the listen queue - Accessing the http://echo/test-broadcast
UPDATED
11.1 Adjust methods for the ExampleEvent to:
public function broadcastOn() { return new Channel('MyChannel'); }
パブリック関数broadcastAs(){リターン 'ExampleEvent'。}
welcome.blade.phpで11.2、BODYタグの前に、アドオン
<script type="text/javascript" src="/js/app.js"></script>
database.phpで11.3、空の文字列値に設定redixプレフィックス
'prefix' => env('REDIS_PREFIX', '')
TO RE-RUN忘れないnpm run dev
とクリアブラウザのキャッシュを
結果