Laravel Socket.I.O vuejs

时间:2018-08-02 07:22:13

标签: laravel socket.io laravel-echo

嗨,我正在尝试与Socket.I.O vuejs laravel连接

我的App.js或Main.js代码中的

  import io from 'socket.io-client';
  import Echo from 'laravel-echo';
  import VueEcho from 'vue-echo';
  import VueSocketio from 'vue-socket.io';

  window.io = require('socket.io-client');

   const EchoInstance = new Echo({
     broadcaster: 'socket.io',
      host: window.location.hostname + ':6001'
  });

  Vue.use(VueEcho, EchoInstance);

在Channels.php中

Broadcast::channel('test-event', function() {
return true;
});

示例事件

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 ExampleEvent implements ShouldBroadcast
  {
      use Dispatchable, InteractsWithSockets, SerializesModels;

/**
 * Create a new event instance.
 *
 * @return void
 */
public function __construct()
{
     return "Hello";
}

/**
 * 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' => 'key'
       ];
  }
 }

在路由web.php中

Route::get('test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);

});

在我的组件文件中

mounted() {
this.$echo.channel("test-event").listen("ExampleEvent", e => {
  console.log(e);
 });
}

根据 https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b

我跑步时

  

/ test-broadcast

它必须在我的about.vue浏览器控制台中做出响应,但是什么也没有显示。能帮上我所缺少的什么吗,谢谢

1 个答案:

答案 0 :(得分:0)

您是否设置了任何队列驱动程序?您将需要配置并运行队列侦听器。所有事件广播都是通过排队的作业完成的。

否则您可以使用ShouldBroadcastNow界面。

示例事件中的更改

use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class ExampleEvent implements ShouldBroadcastNow
  { ...