Laravel5.1 Events Broadcast (event broadcasting)

Source: Internet
Author: User
Event broadcast

Brief introduction

Larvel 5.1 In the new event broadcast function, the role of the server triggered by the event through the WebSocket service notify the client, that is, the browser, the client JS according to the received events, make corresponding actions. This article demonstrates the process of an event broadcast with simple code.

Depend on

    • Redis
    • Nodejs, Socket.io
    • Laravel 5.1

Configuration

In config/broadcasting.php, the following configuration ' default ' = env (' Broadcast_driver ', ' Redis '), using Redis as a means of communication between PHP and JS.
Configure Redis connections in the config/database.php.

Define an event that is broadcast

Depending on the description of the Laravel documentation, to enable the event to be broadcast, you must have the event class implement a Illuminate\contracts\broadcasting\shouldbroadcast interface and implement a method Broadcaston. Broadcaston returns an array that contains the channel (channel) to which the event was 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 is broadcast on.     *     * @return Array     *    /Public Function Broadcaston ()    {        return [' Test-channel '];}    }

The data being broadcast

By default, all public properties in an event are serialized and broadcast. In the above example, $user_id is the attribute. You can also use the Broadcastwith method to explicitly indicate that you want to broadcast the above data. For example:

Public Function Broadcastwith () {    return [' user_id ' = ' = $this->user_id];}

Redis and WebSocket servers

    • Need to start a Redis, the event broadcast is mainly dependent on the Redis sub/pub feature, you can see the Redis document

    • Need to start a websocket server to communicate with 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 (+);    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);});

It is important to note that the definition of the Redis.on method, after receiving the message, sends an event to the client, the event name is Channel + ': ' + message.event.

Client code

Client We also use Socket.io, as a test, the code is as simple as possible, just print one of the received data. 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-Triggered events

An event trigger can be defined directly in the router. 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 is connected successfully.
    • Trigger an event to open another page localhost/event.

At this point, you can see that the first page of the console printed out Object{user_id:3}, indicating that the broadcast was successful.

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

  • Related Article

    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.