Laravel Event Broadcast

Source: Internet
Author: User
Tags redis server

Dependent Laravel (Predis), Redis, Nodejs (Ioredis,socket.io)

1, modify the config\app.php

Add ' Illuminate\broadcasting\broadcastserviceprovider ' to the providers array,

2, modify the broadcast drive mode for config\broadcasting.php

' Default ' = env (' Broadcast_driver ', ' Redis '), changed to Redis Drive

Use Redis as a way to communicate with PHP and JS.

3, Configuration config\database.php

Configure Redis Service Connection parameters

Define an event that is broadcast

<?phpnamespace app\events;use app\events\event;use illuminate\queue\serializesmodels;use  illuminate\contracts\broadcasting\shouldbroadcast;use illuminate\support\facades\session;class  MessageBroadcastEvent extends Event implements ShouldBroadcast{     use SerializesModels;    public  $users;     public   $message  = array ();    protected  $channel;     /**      * Create a new event instance.      *     *  @return  void     */     public function __construct ($users,  $message,  $channel)      {         $this->users =  $users;          $thisMessage = array (             ' id '        =>  $message [' ID '],               ' title '    =>  $message [' title '],               ' content '  =>  $message [' content '],               ' URL '      =>   $message [' url '],              ' time '     => date (' M-d h:i:s ',  strtotime ($message [' created_at ']))              );         $this->channel =  $channel;    }    /**      * Get the channels the event should be broadcast on.      *  broadcast to which channel      *  @return  array     */     public function broadcaston ()     {         return [$this->channel];    }}

By default, all public properties in an event are serialized and broadcast. The above example is $users, $message two properties. can also

Use the Broadcastwith method to clearly indicate what data to broadcast. For example:

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

Redis and WebSocket servers

Relies on the sub/pub capabilities of Redis

Start a node WebSocket server to communicate with client, we use Socket.io

node service-side code saved as Index.js placed in the node service directory

Var app = require (' http '). Createserver (handler); Var io = require (' Socket.io ') ( APP), Var redis = require (' Ioredis '); Var redis = new redis (' 6379 ',  ') 192.168.10.10 ');  //connect Redis server//Listener client port   Here is  6001app.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)     //data sent to the client     message = json.parse (message);     io.emit (channel +  ': '  +  Message.event, message.data);});

Client-side code, as long as the client needs to be broadcast the page correctly references the Node Socket.io module client JS file (this client module file is placed in the project public directory by itself)

<script src= "Js/socket.io/node_modules/socket.io-client/socket.io.js" ></script>// The client also uses Socket.io, the test code: Console printout//connection to the socket server var socket = io (' http://localhost:6001 '); Socket.on (' Connection ', function (data) {console.log (data);}); /Listen to the channel Socket.on (' channel-{{session::get (' Shop ')->id}}:app\\events\\messagebroadcastevent ', function (data) {//        Console output broadcast messages Console.log (message); Here you can do some work to change the structure of the page according to the message received ...});    /can listen to multiple channels socket.on (' Channel-system:app\\events\\messagebroadcastevent ', function (data) {Console.log (data); Here you can do some work to change the structure of the page according to the message received ...}); /Console output connection information console.log (socket);

Trigger event in Project

Broadcast events can be invoked directly in the controller or in the Routing anonymous function

1, direct call in the controller

Which users to send to  id .   Here defines the message receiving user, which is used in the foreground to detect whether the logged-in user is in this array, and the presence of the corresponding instant alert is made. Note: In fact, broadcast messages will be sent to the corresponding channel. $users  = array (1,&NBSP;2);//here can save Send message to  messages  table $message = new message (); $message->title           =  ' Your store has a new sales order '; $ message->content         =  ' Your store has a new sales order, number 1000000 '; $ message->message_type_id = 1; $message->status           = 0; $message->url              =  ' http://www.xxx.com '; $message->save ();//Save send user   to  user_message  table $usermessage  = array (); $time     = date ("Y-m-d h:i:s");foreach  ($users  as   $user)  {      $tmp  = array (          ' Created_at '  => $time,         ' updated_at '  => $time,          ' user_id '     => $user,         ' message_id '  => $message->id,          ' read '         =>0    );     $userMessage []  =  $tmp;} Usermessage::insert ($userMessage);//broadcast channels//We identify channels by store ID, so that front-end user pages are also based on store ID identification to listen to their store channels, can do the store broadcast messages can only broadcast to the store users $ channel =  ' channel-'  . session::get (' shop ')->id; //$channel  =  ' Channel-system ';  //other channels//$response  = event (new messagebroadcastevent ($users,  $message ,  $channel)); Event::fire (new messagebroadcastevent ($users,  $message,  $channel))  //both of these can trigger events

2, direct call in the route

Example code route::get ('/event ', function () {Event::fire (New \app\events\someevent (3)); Return "Hello World";});

Use:

The node WebSocket server must be turned on. I installed node in the C-drive under the native Windows, the server code is placed in this directory, into CMD

Terminal, execute command, node index.js start server.

Open the client page with the Socket.io code in the package, waiting to be broadcast

Trigger our Background Broadcast event (execute the corresponding controller code)


Laravel Event Broadcast

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.