Laravel implementation of real-time application building method Introduction

Source: Internet
Author: User
Tags server port
This article mainly introduces to you about Laravel construction of a real-time application of an implementation method, instant communication in our daily development often encounter, this article through the sample code introduced in very detailed, the need for friends can reference, the following with small series to learn together.

Apps for instant interaction

Everyone should have some experience, in modern WEB applications, many scenarios need to apply to instant messaging, such as the most common payment callbacks, and three-party login. These business scenarios are basically required to follow the following processes:

    • The client triggers the related business and generates actions for third-party applications (such as payments)

    • Client waits for server-side response results (user completes third-party app operation)

    • Third-party app Notification Server processing results (payment complete)

    • Server-side notification client processing results

    • Client feedback based on results (jump to payment success page)

In the past, in order to achieve this kind of instant communication, so that the client can correctly respond to processing results, the most common technique is polling, because the HTTP protocol is unidirectional, the client can only over and over again to proactively ask the server processing results. This approach has obvious flaws, occupy the server resources do not say, also can not get the server processing results in real time.

Now, we can use the WebSocket protocol to handle real-time interaction, which is a two-way protocol that allows the server to proactively push information to the client. In this article we will build real-time interactions with Laravel's powerful event system. You will need to use the following knowledge:

    • Laravel Event

    • Redis

    • Socket.io

    • node. js

Redis

Before we get started, we need to start a Redis service and configure it in the Laravel app, because in the process we need to use Redis's subscription and publishing mechanism to enable Instant messaging.

Redis is an open source, efficient key-to-value storage system. It is usually used as a data structure server to store key-value pairs, which can support strings, hashes, lists, sets, and ordered combinations. Using Redis in Laravel you need to install the Predis/predis package file through Composer.

Configuration

The Redis configuration file in the app is stored in config/database.php, where you can see a redis array with information about the Redis service:


' Redis ' = [' cluster ' + false, ' default ' = = ' host ' = ' 127.0.0.1 ', ' port ' = 6379, ' database ' = 0, ],]

If you modify the ports of the Redis service, keep the ports in the configuration file consistent.

Laravel Event

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

Broadcast events

In many modern applications, Web Sockets are used to implement the user interface for real-time interaction. When some data is changed on the server, a message is passed through the WebSocket connection to the client for processing.

To help you build this type of app. Laravel makes broadcasting events through WebSocket connections very simple. Laravel allows you to broadcast events to share the name of the event to your server and to the 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, and we will use Redis as the broadcast driver, where we need to rely on the Predis/predis class library.

Since the default broadcast driver is using pusher, we need to set it in the. env file. BROADCAST_DRIVER=redis

We create a Wechatloginedevent event class to broadcast after a user scans the login:


<?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, $c Hannel) {  $this->token = $token;  $this->channel = $channel; }/**  * Get The channels the event should is broadcast on.  *  * @return Array *  /Public Function Broadcaston () {  return [$this->channel];}/**  * Get the name The event should is broadcast on.  *  * @return String *  /Public Function Broadcastas () {  return ' Wechat.login ';}}

One of the things you need to notice is that the Broadcaston method should return an array that represents the channel you want to broadcast, and Broadcastas returns a string that represents the event that was triggered by the broadcast, Laravel the default is to return the full class name of the event class, which is App\events\ Wechatloginedevent.

The most important thing is that you need to manually enable the class to implement the Shouldbroadcast contract. Laravel the namespace has been added automatically when the event is generated, and the contract only constrains the Broadcaston method.

The event completion is then triggered, and a simple line of code can:


Event (New Wechatloginedevent ($token, $channel));

This action automatically triggers the execution of the event and broadcasts the information. The broadcast operation is based on the Redis subscription and publishing mechanism.

Redisbroadcaster will publish the data in the event that allows for public access through a given channel. If you want to have more control over the exposed data, you can add the Broadcastwith method to the event and 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 to the Redis release to subscribe, and the information can be forwarded to the WebSocket protocol, here we can borrow node. js and Socket.io to easily 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 (+); 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 to introduce the Socket.io server and listen on port 6001, borrow Redis's psubscribe instructions to use wildcards for fast bulk subscriptions, and then forward messages through WebSocket when the message is triggered.

Socket.io Client

In the Web front end, we need to introduce the Socket.io client to enable communication with the server port 6001 and subscribe to the 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 communication closed loop is over, and the development process looks like this:

    • Build an event in Laravel that supports broadcast notifications

    • Set up the channels and event names that need to be broadcast

    • Set the broadcast to use the Redis driver

    • Provides a continuous service for subscribing to a Redis publication and pushing the release to the client via the WebSocket protocol

    • The client opens the service-side WebSocket tunnel and subscribes to the event, responding to the push of the specified event.

Summarize

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.