简介配置 redis + socket 配置广播消息。
composer require predis/predis
;config/app
中的注释;App\Providers\BroadcastServiceProvider::class
.env
BROADCAST_DRIVER=redis
app/Events/MessageSend.php
;class MessageSend implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastAs()
{
return 'message.send';
}
public function broadcastOn()
{
return new Channel('message.send');
}
}
class PrivateMessageSend implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $toUserId;
public $message;
public function __construct($toUserId, $message)
{
$this->toUserId = $toUserId;
$this->message = $message;
}
public function broadcastAs()
{
return 'private.message.send';
}
public function broadcastOn()
{
return new PrivateChannel('private.message.send.' . $this->toUserId);
}
}
// routes/channels.php
Broadcast::channel('private.message.send.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
class SendMessage extends Command
{
protected $signature = 'message:send {user=0}';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$userId = intval($this->argument('user'));
$message = "hello";
if($userId > 0) {
event(new PrivateMessageSend($userId, $message)); // 触发事件
} else {
event(new MessageSend($message)); // 触发事件
}
$this->info('发送消息 : ' . json_encode($message) );
}
}
npm install -g laravel-echo-server
laravel-echo-server init
创建配置文件{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": false,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
npm install --save laravel-echo
npm install --save socket.io-client
//src/app/core/socket/socket.service.ts
import { Inject, Injectable } from '@angular/core';
import { environment } from '@env/environment';
import Echo from 'laravel-echo'
import { DA_SERVICE_TOKEN, TokenService } from '@delon/auth';
import { LayoutModule } from '../../layout/layout.module';
import { NzMessageService } from 'ng-zorro-antd';
import { SettingsService } from '@delon/theme';
(<any>window).io = require('socket.io-client');
@Injectable()
export class SocketService {
echo: any;
constructor(
private settingService :SettingsService,
@Inject(DA_SERVICE_TOKEN) private tokenService: TokenService) { }
public init(): void {
if (!environment.production) {
console.log(
`%c SOCKET: 初始化 `,
`background:blue;color:#fff`,
);
}
// 记得获取新的token后也要更新
let token = this.tokenService.get().token;
this.echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {headers: {Authorization: 'Bearer ' + token}}
});
}
public destroy() :void {
if(!this.echo) return;
let userId = this.settingService.user.id;
this.echo.leave(`message.send`);
this.echo.leave(`private.message.send.${userId}`);
this.echo.disconnect();
}
}
SocketService
this.socketService.init();
<script type="text/javascript" src="http://localhost:6001/socket.io/socket.io.js"></script>
(window as any).global = window;
本文为秋叶听风原创文章,转载无需和我联系,但请注明来自秋叶听风博客http://ice90.cn
最新评论