Laravel5.1 event broadcast (EventBroadcasting)

Source: Internet
Author: User
Introduction to Laravel5.1 EventBroadcasting

Larvel 5.1 adds the event broadcast function to notify the client of events triggered on the server through the websocket service, that is, the browser. based on the received events, the client js, make corresponding actions. This article uses simple code to demonstrate an event broadcast process.

Dependency
  • Redis
  • Nodejs, socket. io
  • Laravel 5.1
Configuration

In config/broadcasting. php, 'default' => env ('broadcast _ DRIVER ', 'redis') is configured as follows. redis is used as the communication mode between php and js.
Configure the redis connection in config/database. php.

Define a broadcast event

According to the instructions in Laravel, to broadcast an Event, you must enable the Event class to implement an Illuminate \ Contracts \ Broadcasting \ ShouldBroadcast interface and a method of broadcastOn. BroadcastOn returns an array containing the channel to which the event is sent ). As follows:

namespace App\Events;use App\Events\Event;use Illuminate\Queue\SerializesModels;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class SomeEvent extends Event implements ShouldBroadcast{    use SerializesModels;    public $user_id;    /**     * Create a new event instance.     *     * @return void     */    public function __construct($user_id)    {        $this->user_id = $user_id;    }    /**     * Get the channels the event should be broadcast on.     *     * @return array     */    public function broadcastOn()    {        return ['test-channel'];    }}
Broadcast Data

By default, all the public attributes in the Event are serialized and then broadcast. In the preceding example, the $ user_id attribute is used. You can also use the broadcastWith method to explicitly point out the need to broadcast the above data. For example:

public function broadcastWith(){    return ['user_id' => $this->user_id];}
Redis and Websocket servers
  • You need to start a Redis instance. event broadcast mainly depends on redis's sub/pub function. for details, see the redis documentation.

  • To enable a websocket server to communicate with the client, we recommend using socket. io. the code is as follows:

    var app = require('http').createServer(handler);var io = require('socket.io')(app);var Redis = require('ioredis');var redis = new Redis('6379', '192.168.1.106');app.listen(6001, function() {    console.log('Server is running!');});function handler(req, res) {    res.writeHead(200);    res.end('');}io.on('connection', function(socket) {    console.log('connected');});redis.psubscribe('*', function(err, count) {    console.log(count);});redis.on('pmessage', function(subscribed, channel, message) {    console.log(subscribed);    console.log(channel);    console.log(message);    message = JSON.parse(message);    io.emit(channel + ':' + message.event, message.data);});

Note the definition of the redis. on Method. after receiving a message, send an event to the client named channel + ':' + message. event.

Client code

The client also uses socket. io for testing. the code is simplified as much as possible and only one accepted data is printed. As follows:

var socket = io('http://localhost:6001');socket.on('connection', function (data) {    console.log(data);});socket.on('test-channel:App\\Events\\SomeEvent', function(message){    console.log(message);});console.log(socket);
Server trigger event

Define an event trigger in the router directly. As follows:

Route::get('/event', function(){    Event::fire(new \App\Events\SomeEvent(3));    return "hello world";});
Test
  • Start redis
  • Start websocket
  • Open the page with the client code and you can see that the websocket has been successfully connected.
  • Trigger event to open localhost/event on another page.

At this time, we can find that the first page of the console prints the Object {user_id: 3}, indicating that the broadcast is successful.

I recorded a teaching video. if you do not understand it, please refer to this video.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.