Laravel describes how to build real-time applications.

Source: Internet
Author: User

Laravel describes how to build real-time applications.

Instant interaction applications

We should all understand that in modern Web applications, instant messaging is required in many scenarios, such as the most common payment callback and third-party login. These business scenarios basically need to follow the following process:

  • The client triggers related services and generates operations (such as payment) for third-party applications)
  • The client waits for the response from the server (the user completes operations on third-party applications)
  • Third-party applications notify the server of the processing result (Payment completed)
  • The server notifies the client of the processing result.
  • The client sends feedback based on the result (jump to the payment success page)

In the past, in order to achieve this kind of instant communication and allow the client to correctly respond to the processing results, the most commonly used technology is round robin, because of the one-way HTTP protocol, the client can only actively query the processing results of the server once. This method has obvious defects. If you use server resources, you cannot obtain server processing results in real time.

Now, we can use the WebSocket protocol to process real-time interaction. 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 interaction. You will need the following knowledge:

  • Laravel Event
  • Redis
  • Socket. io
  • Node. js

Redis

Before starting, we need to enable a redis service and enable the configuration in the Laravel application, because throughout the process, we need to use the redis subscription and publishing mechanism for instant messaging.

Redis is an open-source and efficient key-Value Pair storage system. It is usually used as a data structure server to store key-value pairs. It supports string, hash, list, set, and ordered combination. To use Redis in Laravel, you need to use Composer to install the predis/predis package file.

Configuration

The configuration file of Redis in the application is stored in config/database. php. In this file, you can see a Redis array containing redis service information:

'redis' => [ 'cluster' => false, 'default' => [ 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ],]

If you have modified the port of the redis service, make sure that the port in the configuration file is consistent.

Laravel Event

Here we need to use Laravel's powerful event broadcast capabilities:

Broadcast events

In many modern applications, Web Sockets is used to implement real-time interactive user interfaces. When some data changes on the server, a message is transmitted to the client through a WebSocket connection for processing.

To help you build such applications. Laravel makes it easy to broadcast events through WebSocket connections. Laravel allows you to broadcast events to share the event name to your server and client's JavaScript framework.

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. here we need to rely on the predis/predis class library.

The default broadcast driver uses pusher, so we need to set it in the. env file. BROADCAST_DRIVER=redis.

We create a WechatLoginedEvent event class to broadcast after a user scans for Logon:

<?phpnamespace 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'; }}

Note that the broadcastOn method should return an array that represents the channel to be broadcast, while broadcastAs returns a string that represents the broadcast-triggered event, laravel defaults to the full Class Name of the returned event class, which is App \ Events \ WechatLoginedEvent.

The most important thing is that you need to manually implement the ShouldBroadcast contract for this class. Laravel automatically adds the namespace when generating an event. This contract only limits the broadcastOn method.

After the event is completed, the event is triggered. A simple line of code can be used:

event(new WechatLoginedEvent($token, $channel));

This operation will automatically trigger the event execution and broadcast the information. The underlying layer of this broadcast operation relies on the redis subscription and publishing mechanism.

RedisBroadcaster publishes publicly accessible data in the event through a given channel. If you want to have more control over public data, you can add the broadcastWith Method to the event. It should return an array:

/** * Get the data to broadcast. * * @return array */ public function broadcastWith()  { return ['user' => $this->user->id]; }

Node. js and Socket. io

For the published information, we need a service to connect, so that it can subscribe to the redis release and forward the information using the WebSocket protocol. Here we can borrow Node. js and socket. io is very convenient to build this service:

// server.jsvar 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);});

Here we use Node. js introduces socket. the io server listens to port 6001 and uses the psubscribe command of redis to quickly subscribe to messages in batches using wildcards. Then, when a message is triggered, the message is forwarded through WebSocket.

Socket. io Client

On the web front-end, we need to introduce the Socket. io client to enable communication with the server port 6001 and subscribe to Channel Events:

// client.jslet io = require('socket.io-client')var socket = io(':6001')  socket.on($channel + ':wechat.login', (data) => {  socket.close()  // save user token and redirect to dashboard})

At this point, the entire closed-loop communication has ended, and the development process looks like this:

  • Build an event in Laravel that supports broadcast notifications
  • Set the channel and event name to be broadcast
  • Set broadcast to use redis driver
  • A continuous service is provided to subscribe to redis publishing and push the published content to the client through the WebSocket protocol.
  • The client opens the WebSocket tunnel of the server, subscribes to the event, and responds to the Event Based on the push of the specified event.

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.

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.