我有一个使用这个包(https://github.com/tlaverdure/laravel-echo-server)的小型 Laravel Echo 服务器设置。我有以下设置:
// app.js
import Echo from "laravel-echo";
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://vaprobash.dev:6001'
});
window.Echo.channel('documents-sharing')
.listen("Api\\DocumentShared", (event) => {
console.log(event);
});
.
// server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
redis.subscribe('documents-sharing', function(err, count) {
console.log("subscribed " + count);
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log('Message Received: ', channel, message);
console.log(io.to(channel).emit(message.event, message.data));
});
.
// laravel-echo-server.json
{
"authHost": "http://localhost",
"clients": [
{
"appId": "986bb8954bb1e2e9",
"key": "58ca6a205718590ad5fd88a1afc1877c"
}
],
"database": "redis",
"databaseConfig": {
"redis": {
"port": "6379",
"host": "localhost"
},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "localhost",
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": ""
}
.
// DocumentShared.php
class DocumentShared implements ShouldBroadcast, ShouldBroadcastNow
{
use SerializesModels, InteractsWithSockets;
/**
* @var User
*/
public $user;
/**
* @var Resource
*/
public $resource;
/**
* @var Share
*/
public $share;
/**
* Create a new event instance.
*
* @param User $user
* @param Resource $resource
* @param Share $share
*/
public function __construct(User $user, Resource $resource, Share $share)
{
$this->user = $user;
$this->resource = $resource;
$this->share = $share;
}
public function broadcastOn()
{
return new Channel("documents-sharing");
}
}
.
// app.blade.php
<script src="{{ asset('js/socket.io.min.js') }}"></script>
<script src="{{ asset('js/home.js') }}"></script>
之后我运行:
gulp watch
redis-server
node server.js
laravel-echo-server start
php artisan queue:listen
当/notify
路线被击中时,我触发事件。
Route::get('notify', function() {
$user = User::first();
$resource = Resource::first();
$share = Share::first();
event(new DocumentShared($user, $resource, $share));
return 'done';
});
我可以看到服务器已收到事件并且它没有显示在队列中。