Broadcasting event with Socket.io and Redis in Lar

2019-07-23 16:10发布

I'm trying to create a simple event broadcast option with L5.3 using socket.io and Redis. The things are works fine with server side but not working on the client side. here is my code.

Event code

public $data;

public function __construct($data)
{
    //
    $this->data = $data;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return Channel|array
 */
public function broadcastOn()
{
    return new PrivateChannel('test-channel');
}

Socket.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function(err, count) {
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

View file

<script type="text/javascript">
   var socket = io('http://localhost:3000');

    socket.on('test-channel: App\\Events\\SomeEvent', function(message) {
      alert("not yet reached here")
       jQuery('#dynamic_content').append(message.data.name);
   });
    </script>

event fire code

Route::get('test', function () {
    // Route logic...
    $data = array("id" => "1","name"=>"jobin" , "amount" => "1000");
    Redis::publish('test-channel', json_encode($data));
    event(new App\Events\SomeEvent($data));
     return "event fired";
});

when I visit domain.app/test the node server console already out put the result like below.

Message Recieved: {"id":"1","name":"jobin","amount":"1000"}

I already tried several thread I' still not able to figure out what I'm missing here.

My ENV

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
SESSION_DRIVER=database
QUEUE_DRIVER=redis

only issue is unable to reflect it on client side ,the console of node server and handle method of EventListener are works fine (I can dump the data there).

Any idea guys last 6 hours working on it.

already tried these any hint will highly appreciated . Thank you.

1条回答
Juvenile、少年°
2楼-- · 2019-07-23 16:55

Private channels adds private_ before the name. In you case the channel name will be private_test-channel

查看更多
登录 后发表回答