Search code examples
laravelsocket.iolaravel-echo

Laravel Socket.I.O vuejs


hi i am trying to connect with Socket.I.O vuejs laravel

in my App.js or Main.js code is

  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);

In Channels.php

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

Example event

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'
       ];
  }
 }

in Routes web.php

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

});

in my Components file

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

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

when i run

/test-broadcast

it have to give response in my about.vue browser console , but there is nothing to display at all. can any help what thing i am missing yet , Thanks in Advance


Solution

  • have you setup any queue driver? you will need to configure and run a queue listener. All event broadcasting is done via queued jobs.

    or else you can use ShouldBroadcastNow interface.

    change in you Example Event:

    use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
    
    class ExampleEvent implements ShouldBroadcastNow
      { ...