Detailed explanation of the broadcast module in Laravel learning tutorial
Preface
This article mainly introduces the Laravel broadcast module for your reference. I will not talk about it much below. Let's take a look at the details:
Note:This article analyzes and writes the routing module code based on Laravel 5.4;
Introduction
Broadcast means that the sender sends A message, and each receiver of the subscription channel can receive the message in time. For example, A wrote an article and B commented under the article, on the page, students A can receive A prompt that an article has been commented. This is essentially because A received A broadcast message, this broadcast message is triggered by the comment of B;
In the whole broadcast behavior, there is an important concept: channel, the channel type has
- Public channel
- Private channel
- Channel presence
If the mobile terminal subscribes to the public channel, a message is displayed, indicating that the subscription is successful. When the private channel and the existing channel presence subscribe, a permission verification is sent to the server, check whether you have the permission to subscribe to this channel. The difference between private channel private and the existing channel presence is that private channel private can receive messages sent by other Members, but there is a channel presence, it can also receive information when a user joins or leaves;
Broadcast is suitable for the following scenarios:
- Notification or Signal)
- Notifications are the simplest and most frequently used examples. Signals can also be seen as a form of notification display, but the signal has no UI.
- Activity Streams
- Activity Streams (feeds) is the core of social networks. For example, A can view B's likes in real time and B can view A's comments in real time.
- Chat
- Real-time display of chat Information
Module composition
Demo
Log-driven
Configuration
Modify or add a line to the. env file:BROADCAST_DRIVER=log
;
Broadcast
Direct call
$ Manager = app (Illuminate \ Broadcasting \ BroadcastManager: class); $ driver = $ manager-> connection (); // The first parameter is the channel name, the second parameter is the event name, and the third parameter is the broadcast content $ driver-> broadcast (['Channel _ 1', 'Channel _ 2'], 'login ', ['message' => 'Hello world']);
Because it is a log driver, the broadcast content will be written to the log file configured by the framework, and the output message is as follows:
[2017-08-18 20:45:49] local.INFO: Broadcasting [login] on channels [channel_1, channel_2] with payload:{ "message": "hello world"}
Listen to event broadcast
This call method is used when an event implementing the ShouldBroadcast interface is triggered, broadcast operations will be performed. (also, there is an interface called ShouldBroadcastNow, which is different from the ShouldBroadcast interface, when an event that implements the ShouldBroadcastNow interface is put into the queue, it is put into the queue called sync)
For example,
Step 1: The Illuminate \ Auth \ Events \ Login event is an event that will be triggered after the user logs on successfully. It is slightly modified to implement the broadcast function;
Class Login implements ShouldBroadcast {...... // define the Broadcast channel when an event is triggered. The public function broadcastOn () of the private channel named first-channel is defined here () {return [new PrivateChannel ('first-channel'),];} // custom broadcast name. If the method is not defined, the event name is used by default, the default value here is Illuminate \ Auth \ Events \ Login public function broadcastAs () {return 'login ';}}
Step 2: register the event listener. in app/Providers/EventServiceProvider. php, modify:
protected $listen = [ ...... 'Illuminate\Auth\Events\Login' => [ 'App\Listeners\UserLogin', ],];
The file app/Listeners/UserLogin. php is roughly implemented as follows:
class UserLogin { public function __construct() {} public function handle(Login $event){ \Log::info('Do UserLogin Listener: I was Login'); }}
Step 3: trigger events and send broadcasts. There are several broadcast triggering methods:
Direct event triggering
event(new Illuminate\Auth\Events\Login($user, true));
The help function broadcast indirectly triggers events.
broadcast(new Illuminate\Auth\Events\Login($user, true));
Broadcast management class, indirectly trigger events, and broadcast directly
$manager = app(Illuminate\Broadcasting\BroadcastManager::class);$manager->event(new Illuminate\Auth\Events\Login($user, true));
Broadcast management class that indirectly triggers events and puts them in the queue
$manager = app(Illuminate\Broadcasting\BroadcastManager::class);$manager->queue(new Illuminate\Auth\Events\Login($user, true));
Pusher driver
Pusher is a third-party service. When a server sends a broadcast, it sends a request to Pusher, and then interacts with data through the persistent connection that Pusher maintains with the browser or mobile terminal;
Configuration
You can use the Pusher official website to register user information, obtain your own set of key information, and modify the. env configuration file;
BROADCAST_DRIVER=pusherPUSHER_APP_ID=xxxxxxxxxxxxxxxxxxxxxxPUSHER_APP_KEY=xxxxxxxxxxxxxxxxxxxxxxPUSHER_APP_SECRET=xxxxxxxxxxxxxxxxxxxxxx
Preparations
Event listening
The background event listening still uses the log-driven logon example;
Front end
The following code is introduced to the front-end page:
<Script src = "https://js.pusher.com/4.1/pusher.min.js"> </script> <script> // open the Pusher debugging log Pusher. logToConsole = true; // defines the Pusher variable var pusher = new Pusher ('pusher _ APP_KEY value', {cluster: 'ap1', encrypted: true }); // define the channel and bind the event var channel = pusher. subscribe ('private-first-channel'); channel. bind ('login', function (data) {alert (data) ;}); </script>
If you subscribe to a public channel, the server will not be requested for permission checks; if it is a private channel (the channel name starts with private-) or a channel (the channel name starts with presence ), A permission check request is sent. The corresponding backend needs to define the permissions of private channels and existing channels;
Channel permission Definition
The channel permission is defined in routes/channels. php. The first-channel permission callback function is defined here:
Broadcast::channel('first-channel', function ($user) { return (int) $user->id === 1;});
Some readers may wonder if the channel subscribed to on the front-end page is not private-first-channel? How does the backend define only the first-channel permissions? That is because the backend defined channel is assumed to be A. the private channel name transmitted on Pusher and the browser or mobile end is private-A, and the channel name will be presence-;
Broadcast
Direct Broadcast
$ Manager = app (Illuminate \ Broadcasting \ BroadcastManager: class); $ driver = $ manager-> connection (); // The socket parameter is the socket excluded when a private channel is broadcast, each browser or mobile end is assigned a socket_id $ driver-> broadcast (['private-first-channel'], 'login ', ['user' => ['name' => 'hello'], 'socket' => '2017. 4377611 ']);
Indirect Broadcast
Refer to the indirect broadcast method mentioned in "log-driven;
If you want to send a broadcast Queue (that is, the client that receives the current request does not receive the broadcast message), the following conditions are required:
- The event uses Illuminate \ Broadcasting \ InteractsWithSockets trait;
- The request header sent from the front end must carry the X-Socket-ID information;
- Event-triggered execution of broadcast (new Illuminate \ Auth \ Events \ Login ($ user, true)-> toOthers ();
Redis driver
Configuration
Modify or add a line to the. env file:BROADCAST_DRIVER=redis
;
Broadcast
The principle is to deploy a Socket. IO server on the backend. The Laravel framework will publish a message to the Socket. IO server, and the Socket. IO server will maintain a persistent connection with the browser or mobile server;
This part of the author has not demo yet, and there are still a lot of online entry materials. Knowing the principle makes it much easier to get started with this part of the action;
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.
Appendix
For more information about the same type of articles, see the following:
- Basic knowledge of Laravel college event Broadcasting
- Pusher's understanding