Laravel Echo 在实时聊天中不收听事件

时间:2021-03-02 04:52:39

标签: javascript laravel vue.js websocket pusher

我正在练习使用 laravel vue.js pusher websocket 进行实时聊天。我已经复制了凭据并相应地设置了所有内容,但 Echo 没有监听事件。我通过在监听函数内的日志函数中放置消息来检查它。当我为推送器启用日志时,我收到了事件记录但数据为空

这是我的活动文件

<?php      

  namespace App\Events;

  use App\Models\Message;
  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;
  use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

  class MessageSent  implements ShouldBroadcastNow
  { 
     use Dispatchable, InteractsWithSockets, SerializesModels;
public $messages;
/**
 * Create a new event instance.
 *
 * @return void
 */
public function __construct(Message $messages)
{   
    

    //
    $this->messages = $messages;
    
}

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

  }

================================================ ================================================== ============================

这是我的频道文件

<?php

  use App\Models\Message;
  use Illuminate\Support\Facades\Broadcast;


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

Broadcast::channel('chats',function(Message $messages){
    return $messages;
});

================================================ ================================================== ==

我的 bootstrap.js 文件

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');
Pusher.logToConsole = true;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'e37b09897219d2fbe01c',
    cluster:'ap2',
    encrypted:false,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    
});

================================================ ================================================== =

我的 Vue.js 文件

  <template>
    <div>
        
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    
    <div class="card w-25 h-75 fixed-bottom float-right" id="cardchat" style="display:block">
       <button @click="closeChat" class="btn btn-transparent"> <i class="fa fa-window-close"></i></button>
        <div class="card-header">Student Portal</div>
        <div class="card-body h-50 overflow-auto">
            <span v-for="(row,key,index) in messages" :key="row.id">
                
              
                <div  class="direct-chat-text-mine" :class="row.user_id == chat.user_id?'direct-chat-text-mine':'direct-chat-text'">
                     <span> {{ row.message }}</span>
                      <br>
                      <span class="direct-chat-timestamp" >{{ row.created_at }}</span>
                  </div>
    
            </span>
        </div>
        <div class="card-footer">
            
        <form>
        <input type="text" placeholder="Type to message.." class="form-control" v-model="chat.message" @keyup.enter="newMessage">
        <button type="button" @click="newMessage" class="btn btn-success btn-xs ">Send</button>
        </form>   
        
    </div>
    </div>
    <button @click="openChat" id="chatButton" class="btn btn-transparent fixed-bottom float-right" ><i class="fa fa-comment"></i></button>
        </div>
    </template>
    <script>
    
        var pusher = new Pusher('e37b09897219d2fbe01c', {
          cluster: 'ap2'
        });
    
        var channel = pusher.subscribe('chats');
        channel.bind('chats', function(data) {
          app.messages.push(JSON.stringify(data));
        });
        
    
        
    export default{
        data(){
            return{
                chat:{                
                    message:'',
                },
                messages:{},
            }
        },
       created() {
          console.log("Inside created functions");
            
            window.Echo.channel('chats')
            .listen('App\\Events\\MessageSent', (e) => {
                console.log('ok');
                console.log("listening "+e);
                this.messages.push({
                    message: e.message,
                    
                });
    });     
            
    
        },
        methods:{
            getMessages:function(){
                axios.get('/messages').then((res)=>{
                    this.messages = res.data;
         
                })
            },
             openChat:function(){
                        $('#cardchat').css('display','block');
                        $('#chatButton').css('display','none');
                        this.getMessages();
                        
                    },
                    closeChat:function(){
                        $('#cardchat').css('display','none');
                        $('#chatButton').css('display','block');
                    },
            newMessage:function(){
                
                axios.post('/new/messages',this.chat).then((res)=>{
                    this.getMessages();
                })
            },
        },
        mounted(){
             
            
            this.getMessages();
            
             
           
        }
    }
    </script>

================================================ ================================================== =

广播php文件

================================================ ================================================== ==

'connections' => [

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
            'host' => '127.0.0.1',
            'port' => 6001,
            'scheme' => 'http'
        ],
    ],

================================================ ================================================ Websocket php 文件

'apps' => [
        [
            'id' => env('PUSHER_APP_ID'),
            'name' => env('APP_NAME'),
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'path' => env('PUSHER_APP_PATH'),
            'capacity' => null,
            'enable_client_messages' => false,
            'enable_statistics' => true,
        ],
    ],

================================================ ================================================ 我的控制器文件

  public function store(Request $request)
    {
        //
        $msg  = new Message();
        $msg->message =$request->get('message');
        $msg->user_id =Auth::user()->id;
        $msg->save();
        
      broadcast(new MessageSent($msg))->toOthers();
      
      
        
    }

================================================ ================================================== ================================================== ========================================== 我试过的

我尝试更改频道以仅返回 true 我已登录推送仪表板 我试过添加 .频道名称中的前缀 我试过运行 php artisan queue 命令 我试过清除缓存

0 个答案:

没有答案