laravel56 广播系统

田德运
2023-12-01

events事件:

<?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 News implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;    
    public $token;
    protected $channel;

/*  public function __construct()
    {
    }

    public function broadcastOn()
    {
        return new PrivateChannel('news');
    }*/
    /**
     * Create a new event instance.
     *
     * @param  string $token
     * @param  string $channel
     * @return void
     */
    public $id;
    public $msg;    
    public $userId; 
    public function __construct($id,$userId)
    {
/*        $this->token = $token;
        $this->channel = $channel;*/
        $this->id = $id;
        $this->userId = $userId;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        //return [$this->channel];
        //公有
        //return new Channel('News');
        //私有
        return new PrivateChannel('News-'. $this->userId);
    }

    /**
     * Get the name the event should be broadcast on.
     *
     * @return string
     */
/*    public function broadcastAs()
    {
        //return 'dlogin';
    } */
    public function broadcastWith()
    {
        // 返回当前时间
        return ['name' => 'asfdfa'];
    }       
}

路由:

Route::get('/ship', function (Request $request,Schedule $schedule)
{
    $id = $request->input('id');
    event(new News($id)); // 触发事件
    return Response::make('Order Shipped!');
});

bootstrap.js

import Echo from 'laravel-echo'
 
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://localhost:6001'
});

 

界面:

<!-- 文件保存于 resources/views/layouts/child.blade.php -->
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">	
</head>
<script src="http://localhost:6001/socket.io/socket.io.js"></script>
<body>
<div id='app'></div>
	<div>sdfsf</div>
<script src="{{asset('/js/app.js') }}"></script>
</body>	
<script>
    //console.log(Echo);
    //公有
    //Echo.channel('News')
    //私有
    Echo.private('News')
        .listen('News', (e) => {
            // 如果有广播过来你可以进行逻辑操作,比如给用户一个通知
            console.log(e.name)
        });
</script>        
</html>


两篇很好的参考文档:

https://blog.csdn.net/xinzi11243094/article/details/80186503

https://laravel-china.org/index.php/articles/15031/simple-16-steps-to-go-through-the-use-of-laravel-echo

 类似资料: