


Detailed explanation of how Laravel-echo-server builds real-time applications
The following tutorial column from Laravel will introduce to you how to use Laravel-echo-server to build real-time applications. I hope it will be helpful to everyone!
In my opinion, real-time communication is the future of APP applications. Socket services are usually not easy to implement, but the Laravel Echo service changes this situation.
In this article, I will briefly introduce how to create a running Socket service and broadcast events on this service. (https://github.com/tlaverdure/laravel-echo-server, Laravel support documentation: https://learnku.com/docs/laravel/5.6/broadcasting#driver-prerequisites)
It is It's completely free, you just need to run your own Socket service. You can also use Laravel's default integrated Pusher. The only disadvantage is that it is limited and you need to pay if you exceed the limit. I prefer to structure these things myself.
Requirements:
- Laravel framework (this tutorial uses version 5.6)
- Redis service
- Basic Laravel knowledge
##Install laravel-echo-server
First we need to install laravel-echo-server globally , you just need to enter the following command in the terminal.$ npm install -g laravel-echo-serverAfter the installation is completed, open your Laravel application, or start a new test project:
$ composer create-project --prefer-dist laravel/laravel echo-testNext, install Predis for our application:
$ composer require predis/predisAfter the installation is completed , switch to the project root directory, and initialize the Socket service:
$ laravel-echo-server initAfter executing this command, you will be asked for some configuration information about the Socket service. You can fill it in according to your own situation:
Remember that in a production environment, you should turn off your developer mode whenever you use it.
We can try to start the service and see if it is running normally:$ laravel-echo-server startThe output will look like this:
Configure Laravel to make Laravel Echo Server work properly
Open yourconfig/app.php Detailed explanation of how Laravel-echo-server builds real-time applications and cancel
BroadcastServiceProvider Comments in this Providers array:
App\Providers\BroadcastServiceProvider::class,This Provider will start broadcast routing (you may have already
routes/channels.php Already seen in the Detailed explanation of how Laravel-echo-server builds real-time applications)
.env Detailed explanation of how Laravel-echo-server builds real-time applications and modify the value of
BROADCAST_DRIVER to what you have in laravel-echo-server The value defined during initialization (Redis or Log). In this tutorial we will use the Redis driver.
Also modify
QUEUE_DRIVER to any queue driver you like. In this example you can easily change it to the Redis driver because you have it installed and running earlier.
$ npm install --save socket.io-client $ npm install --save laravel-echo(You may need to run
npm before running this install to install Laravel and related dependencies)
resources/assets/js/bootstrap.js Detailed explanation of how Laravel-echo-server builds real-time applications, or your own JS Detailed explanation of how Laravel-echo-server builds real-time applications that introduces all the JS basic code.
import Echo from 'laravel-echo' window.io = require('socket.io-client'); window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });Now we are ready to listen for messages on the channel! I will explain how to open a channel in this tutorial, and then start listening to our first channel:
window.Echo.channel('test-event') .listen('ExampleEvent', (e) => { console.log(e); });We tell the program through JS code that we subscribe to the channel named 'test-event', and listen to it 'ExampleEvent' event (this is the class name of the event, you can also customize it according to your needs). Let's create this event class:
$ php artisan make:event ExampleEventThis will create an event class called
ExampleEvent.php under the
App/Events directory
Let's slightly adjust this event class so that it can run normally in our Socket service. First, make sure your event class inherits from the
ShouldBroadcast interface, like the following;
class ExampleEvent implements ShouldBroadcastNext scroll down to find the
broadcastOn function, modify it so that we can broadcast on the correct channel:
public function broadcastOn() { return new Channel('test-event'); }Let's create a new function below so we can have some instance data:
public function broadcastWith() { return [ 'data' => 'key' ]; }This function is called when the event is called, and it will return the data to your Socket service. Now let’s start trying it! Open your
routes/web.php Detailed explanation of how Laravel-echo-server builds real-time applications and add a test route:
Route::get('test-broadcast', function(){ broadcast(new \App\Events\ExampleEvent); });
(有很多种方式来广播 ExampleEvent
类 ,在这个示例中我使用 Laravel 提供的 broadcast()
助手,在我看来这是最简洁的方式)
启动队列监听:
$ php artisan queue:listen --tries=1
浏览器打开一个包含 JS 文件的页面(可以是 Laravel 默认的欢迎页面),这是第一个页面,请不要关闭次页面,我们已经在此页面上订阅了 Socket 服务。
接下来打开另一个页面访问 /test-broadcast
,这将会返回一个空白页面,但是它将会通过你的 ExampleEvent
类广播到你的 Socket 服务上。返回到我们的第一个页面,打开浏览器控制台,应该可以看到类似信息:
正如你所看到的,数据通过这种形式展示在我们的客户端。你能输入任意数据通过你的 ExampleEvent
类来广播他们,这些数据可以是新闻更新,页面更新,总浏览量或者更多。
因为我们有在 laravel-echo-server 配置中有设置开发者模式,所以你能看到 Socket 服务上的所有基本信息:
现在你已经安装并运行了一个基本的 Socket 服务!但这并不是全部,你可以根据这个来做更多的事情,比如为单个用户提供认证的私有渠道。(当您想广播订单更新或私人消息时)
要做到这一点,我建议你去查看 Laravel 文档了解更多相关的内容。通过这个主题你能做很多事情,让你的应用程序变得更加神奇。你可以在这里找到相应的文档:
Broadcasting - Laravel - The PHP framework for web artisans.laravel.com
其他: 在生产环境中运行
正如我之前所说,你必须在 laravel-echo-server.json
配置文件中禁用开发者模式。 当然在服务器上你可以忽略这个文件,重新初始化它,因为你的主机可能和本地不同。
你还需要保持你的 Socket 服务在你的生产环境中运行,你可以用 Supervisor ,但是我通常使用 PM2 ,它可以方便快速的管理你的服务。 (http://pm2.keymetrics.io/)
这里是我使用 PM2 的 Socket.sh 基本配置:
#!/usr/bin/env bash laravel-echo-server start
安装了 PM2 后, 你可以通过 pm2 start socket.sh
命令来启动脚本,运行你的 Socket 服务。
我希望它能够帮助到你。 这篇文章主要介绍的是一些基础知识,接下来我们会继续讨论广播路由的授权和不同的广播频道。
感谢你的阅读!
英文原文地址:https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b
译文地址:https://learnku.com/laravel/t/13101/using-laravel-echo-server-to-build-real-time-applications
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Detailed explanation of how Laravel-echo-server builds real-time applications. For more information, please follow other related articles on the PHP Chinese website!

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor
