This article mainly introduces you to an implementation method of building instant applications in Laravel. Instant messaging is often encountered in our daily development. This article introduces it in detail through sample code. Friends who need it can refer to it. Let’s learn with the editor below. I hope to be helpful.
Instant interactive applications
Everyone should have experienced that instant messaging is required in many scenarios in modern Web applications. For example, the most common payment callback is related to third-party login. These business scenarios basically need to follow the following process:
The client triggers related businesses and generates third-party application operations (such as payment)
The client waits for the server response result (the user completes the operation of the third-party application)
The third-party application notifies the server of the processing result (payment is completed)
The server notifies the client of the processing results
The client makes feedback based on the results (jumps to the payment success page)
In In the past, in order to achieve this kind of instant communication and allow the client to respond correctly to the processing results, the most commonly used technology was polling. Because of the one-way nature of the HTTP protocol, the client could only actively ask the server for the processing results over and over again. This method has obvious flaws. Not only does it occupy server-side resources, it also cannot obtain server-side processing results in real time.
Now, we can use the WebSocket protocol to handle real-time interactions. It is a two-way protocol that allows the server to actively push information to the client. In this article we will use Laravel's powerful event system to build real-time interactions. You will need the following knowledge:
Laravel Event
Redis
Socket.io
Node.js
#Redis
Before we begin, We need to open a redis service and configure and enable it in the Laravel application, because throughout the process, we need to use redis's subscription and publishing mechanism to achieve instant messaging.
Redis is an open source and efficient key-value storage system. It is usually used as a data structure server to store key-value pairs, and it can support strings, hashes, lists, sets and ordered combinations. To use Redis in Laravel you need to install the predis/predis package file through Composer.
Configuration
The Redis configuration file in the application is stored in config/database.php. In this file, you can see a The redis array containing the Redis service information:
'redis' => [ 'cluster' => false, 'default' => [ 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ], ]
If you modify the port of the redis service, please keep the port in the configuration file consistent.
Laravel Event
Here we need to use Laravel’s powerful event broadcasting capabilities:
Broadcast Event
Many modern applications use Web Sockets to implement real-time interactive user interfaces. When some data changes on the server, a message is delivered to the client for processing via the WebSocket connection.
To help you build this type of application. Laravel makes it easy to broadcast events over a WebSocket connection. Laravel allows you to broadcast events to share the event name to your server-side and client-side JavaScript frameworks.
Configuration
All event broadcast configuration options are stored in the config/broadcasting.php configuration file. Laravel comes with several available drivers such as Pusher, Redis, and Log. We will use Redis as the broadcast driver, which requires the predis/predis class library.
Since the default broadcast driver uses pusher, we need to set BROADCAST_DRIVER=redis
in the .env file.
We create a WechatLoginedEvent event class to broadcast after the user scans WeChat login:
<?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class WechatLoginedEvent extends Event implements ShouldBroadcast { use SerializesModels; public $token; protected $channel; /** * Create a new event instance. * * @param string $token * @param string $channel * @return void */ public function __construct($token, $channel) { $this->token = $token; $this->channel = $channel; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return [$this->channel]; } /** * Get the name the event should be broadcast on. * * @return string */ public function broadcastAs() { return 'wechat.login'; } }
You need to note that the broadcastOn method should return an array, which represents the channel to be broadcast, and broadcastAs returns a string, which represents the event triggered by the broadcast. Laravel's default is to return the full class name of the event class. Here is App\Events\WechatLoginedEvent.
The most important thing is that you need to manually Let this class implement the ShouldBroadcast contract. Laravel has automatically added this namespace when generating events, and this contract only constrains the broadcastOn method.
After the event is completed, the next step is to trigger the event. A simple line of code is enough:
event(new WechatLoginedEvent($token, $channel));
This operation will automatically trigger the execution of the event and broadcast the information. The underlying broadcast operation relies on the subscription and publishing mechanism of redis.
RedisBroadcaster will publish the publicly accessible data in the event through the given channel. If you want to have more control over the exposed data, you can add the broadcastWith method to the event, which should return an array:
/** * Get the data to broadcast. * * @return array */ public function broadcastWith() { return ['user' => $this->user->id]; }
Node.js and Socket.io
对于发布出去的信息,我们需要一个服务来对接,让其能对 redis 的发布能够进行订阅,并且能把信息以 WebSocket 协议转发出去,这里我们可以借用 Node.js 和 socket.io 来非常方便的构建这个服务:
// server.js var app = require('http').createServer(handler); var io = require('socket.io')(app); var Redis = require('ioredis'); var redis = new Redis(); app.listen(6001, function () { console.log('Server is running!') ; }); function handler(req, res) { res.writeHead(200); res.end(''); } io.on('connection', function (socket) { socket.on('message', function (message) { console.log(message) }) socket.on('disconnect', function () { console.log('user disconnect') }) }); redis.psubscribe('*', function (err, count) { }); redis.on('pmessage', function (subscrbed, channel, message) { message = JSON.parse(message); io.emit(channel + ':' + message.event, message.data); });
这里我们使用 Node.js 引入 socket.io 服务端并监听 6001 端口,借用 redis 的 psubscribe 指令使用通配符来快速的批量订阅,接着在消息触发时将消息通过 WebSocket 转发出去。
Socket.io 客户端
在 web 前端,我们需要引入 Socket.io 客户端开启与服务端 6001 端口的通讯,并订阅频道事件:
// client.js let io = require('socket.io-client') var socket = io(':6001') socket.on($channel + ':wechat.login', (data) => { socket.close() // save user token and redirect to dashboard })
至此整个通讯闭环结束,开发流程看起来就是这样的:
在 Laravel 中构建一个支持广播通知的事件
设置需要进行广播的频道及事件名称
将广播设置为使用 redis 驱动
提供一个持续的服务用于订阅 redis 的发布,及将发布内容通过 WebSocket 协议推送到客户端
客户端打开服务端 WebSocket 隧道,并对事件进行订阅,根据指定事件的推送进行响应。
相关推荐:
详解Laravel实现supervisor执行异步进程的方法
The above is the detailed content of Detailed explanation of Laravel's method of building instant applications. For more information, please follow other related articles on the PHP Chinese website!