Home > PHP Framework > Laravel > body text

Teach you how to use laravel-websockets to build a 'low-profile' broadcast system

藏色散人
Release: 2023-01-05 21:15:46
forward
1961 people have browsed it

This article brings you relevant knowledge about Laravel, which mainly introduces how to use laravel-websockets to implement a "low-configuration version" broadcast system. Friends who are interested should take a look at it. I hope it will be helpful to everyone. helpful.

Teach you how to use laravel-websockets to build a 'low-profile' broadcast system

Preface

I found several tutorials on the Internet without success, and then I continued to study one tutorial and finally succeeded. Then I wrote this tutorial, hoping to help people who are as stupid as me. Also, I hope not to mislead readers. I hope readers will not trust my tutorial too much. I actually succeeded in a daze, and there may be pitfalls in this tutorial of mine. Another point is that I feel that my research process seems to be quite fruitful. If you have enough time, I suggest you do your own research.

At the beginning of the tutorial, I will briefly introduce how I came up with the method introduced in this tutorial. I suggest that people who read the tutorial pay attention to this part, because I suspect that Laravel or related libraries may become incompatible or confusing once they are updated, and then there will be problems again. At that time, readers may need to do their own research.

Why do I say it is a general introduction? Because I feel that many places were created by me. In addition, it may require some unspeakable experience.

Try to reduce the size of the experimental subjects and look for tutorials with fewer steps

At first I followed the Chinese version of the official document, but later I found that it was too complicated and I might have made a mistake. will fail. And sometimes there is not even an error message. Even if there is an error message, either it cannot be found or there are too many questions with completely different answers. If you reduce the scale as much as possible, you should be able to avoid as many pitfalls as possible.

Decompose the task so that you can get feedback on the success of the subtasks

At first, I followed it step by step, and then finally saw whether it was successful. Later I found that this method was too inefficient. Then I found that some sub-steps can be judged by some methods to determine whether they are successful. For example, after laravel-websockets is successfully installed, the dashboard can be opened. It's /laravel-websockets . There is also code to send broadcasts. If successful, you can see the effect in the dashboard mentioned earlier. Finally, if everything is successful, you can see the effect in the browser. So later on, if I didn’t succeed at the current stage, I wouldn’t continue doing it, and I would continue to study what went wrong at this stage.

Log more

I discovered by logging that the client's Echo was not initialized successfully at all because there were fewer parameters. There seemed to be an error message before, but I didn't seem to understand it. By outputting two different Logs before and after initializing Echo, I found that only the former one was executed, and the latter one was not executed at all, so I came to the conclusion that the program stopped executing when it encountered an error.

Try to be familiar with the subject being tested

For example, I did not find any relevant information about a certain error report. But later I found that a certain word in it appeared in the configuration, so I just changed that configuration and it was fine. It's this: "Uncaught Options object must provide a cluster". But then I found a method on the Internet that was the same as mine. Maybe I had seen that method before, maybe because the poster said it was useless, so I didn’t try it.

Comprehensive information from all parties, especially those that are successful

Although it may not be easy to use and may even be misleading, I believe that more information will be more helpful in solving the problem questionable. For example, I searched for "laravel broadcast" on Bilibili and watched a few videos. Also searched some unofficial documentation tutorials.

If the search error message is useless or there are too many search results, take a look at the code

But I feel that the probability of this being useful is low, so use it when you have no other options. Through this method, I found that I uncommented one less line when uncommenting the code, and then a very strange error message appeared.

Even if you succeed, don’t be too happy. Practice it a few more times.

The more steps you have, the easier it is to have problems. There are so many steps in this broadcasting system. The more you practice, the more familiar you will become.

Try to choose updated tutorials

I usually add a condition within one year to the search engine.

Search engine oriented programming

It feels like more than half of the problems this time were solved through search engines, and there seemed to be very few parts that were completely solved by myself.

Ontology

Some aspects of my tutorial are quite lengthy. It starts with creating a project and also mentions configuring the database. Advanced readers may ignore some content. As for high-end readers, there shouldn't be any need to read my stuff. However, I have basically no introduction to the command. If you need it, I recommend reading the following English article.
Memo

This is a public channel. There are also queues that use the default sync, which is said to be only used in development environments. In short, my tutorial is probably quite crippled, but if you run through it, you should be able to use it as a starting point to experiment with new configurations and add new functions according to the official documents.

My tutorial mainly refers to this article: How to use Laravel WebSockets.

Create project

Run the following command in Apache24\htdocs or similar place:

composer create-project laravel/laravel bc
Copy after login

Run the following command in the project path:

php artisan serve
Copy after login

Note After running the above command, the current command line window generally cannot run commands, and a command line window needs to be restarted. You want to continue running commands in the current command line window unless you cooperate with commands running in the background.

Configuring database information

You need to create a database before configuring the database. I use test. However, even if it is not created, it will be prompted to create it when migrating. I almost forgot about this because I have never deleted this database before.

.env

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=testDB_USERNAME=rootDB_PASSWORD=1234
Copy after login

Be careful to fill in the actual information of your database, don't copy my configuration.

Install the server-side package beyondcode/laravel-websockets

Run the following command in the project path:

composer require beyondcode/laravel-websockets
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"php artisan migrate
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
Copy after login

Install pusher

Run the following command in the project path Command:

composer require pusher/pusher-php-server
Copy after login

Note that this article is different from the article I referred to. The one I installed should be the latest version. The original text seems to have a specific version.

Configuring Laravel WebSockets

.env

BROADCAST_DRIVER=pusherPUSHER_APP_ID=12345PUSHER_APP_KEY=ABCDEFGPUSHER_APP_SECRET=HIJKLMNOPPUSHER_HOST=127.0.0.1PUSHER_PORT=6001PUSHER_SCHEME=httpPUSHER_APP_CLUSTER=mt1
Copy after login

Note that this is also different from the English article I referred to. I have obsessive-compulsive disorder and feel that changing to .env is more elegant. After all, other places will read .env first. It feels like .env is more like a function. If you change one place, you don’t need to modify all the calling places. I feel like there's something wrong with the previous sentence, maybe that's what it means.

Please note that the values ​​from the second to fourth items are filled in casually.

Run Laravel WebSockets server

Run the following command in the project path:

php artisan websockets:serve
Copy after login

This is also the current command line after running Commands cannot be entered in the window. [Recommended learning: laravel video tutorial]

and then enter 127.0.0.1:8000/laravel-websockets in the browser address bar to see whether the previous operation was successful. . If you are not running the server through "php artisan serve", the port may be different. Click the Connect button and if something appears under Events, it should be a phased success. Note that this webpage is very slow to open without that, at least it is very slow for me. Because there is a js library in it that is very slow to download. Note that the following behavior of changing the blade template is optional! In addition, I don’t know if there is any problem with the CDN below. After all, it doesn’t seem to be a CDN from a major manufacturer. If you are too slow and don't want to do that, you can replace

<script  src="https://www.php.cn/link/19e0c9edc141240b5de750fa83ba1bed"></script>
Copy after login

in vendor\beyondcode\laravel-websockets\resources\views\dashboard.blade.php with

<script  src="https://cdn.bootcdn.net/ajax/libs/plotly.js/2.17.0/plotly.min.js"></script>
Copy after login

This file was found by directly searching cdn.plot.ly/plotly-latest.min.js using the VS Code search function. In addition, in the Firefox developer tools network, I found that the loading speed of this js library is slow. In addition, it would be inelegant to directly change files in such places.

Create Event

Run the following command in the project path:

php artisan make:event NewTrade
Copy after login

app\Events\NewTrade.php

<?php
namespace App\Events;use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewTrade implements ShouldBroadcast{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $trade;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($trade)
    {
        $this->trade = $trade;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('trades');
    }}
Copy after login

Run the following command in the project path :

php artisan tinker
Copy after login

After running this command, Laravel's interactive interpreter will be started. I understand that entering some statements can be executed directly. There are also some other practical commands. This also means that after running, the current command line window cannot enter normal system commands, but after this command line window, php statements must be entered. By the way, the terminal in VS Code cannot use Ctrl V in tinker, but the right-click function can be used to paste.

Then run the following command in the command line window where php artisan tinker was executed above:

event (new \App\Events\NewTrade('test'))
Copy after login
Copy after login

After that, you can run the command line window mentioned above 127.0.0.1:8000/laravel -websockets page sees the message sent. If you can see it, it means that the stage is successful.

Install the client package laravel-echo

Run the following command in the project path:

npm installnpm install --save-dev laravel-echo pusher-js
Copy after login

resources\js\bootstrap.js

import Echo from 'laravel-echo';import Pusher from 'pusher-js';window.Pusher = Pusher;window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,});
Copy after login

Pay attention here It is also different from the English article I referred to. I just uncommented those things in that file and added the line "cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER," at the end.

Run the following command in the project path:

npm run dev
Copy after login

This also means that after running this, commands cannot be entered in the current command line window.

添加客户端脚本

在文件
resources\views\welcome.blade.php
的 head 标签的结尾添加以下代码:

        @vite('resources/js/app.js')        <script>
            window.onload = function(){
                Echo.channel('trades')
                .listen('NewTrade', (e) => {
                    console.log(e.trade);
                });
            };
        </script>
    </head>
Copy after login

注意这里也跟我参考的那篇英文文章不一样。改了两处,一个是导入 app.js 的方法换了。另外套了一层 window.onload。

然后在浏览器的地址栏输入 127.0.0.1:8000/ 启动开发者工具并切换到控制台标签页。然后再在前面运行过 php artisan tinker 的那个命令行窗口中执行以下命令:

event (new \App\Events\NewTrade('test'))
Copy after login
Copy after login

最后切换到前面提到的开发者工具中的控制台标签页,应该能看到一条“test”消息。能看到就说明最终成功了。

结语

我只是个菜狗,不要问我太复杂的问题。我从开始搞这个广播系统到最终成功好像用了两三天的时间,就凭这个时间你应该就能体会到我有多菜了。

最后因为我是菜狗,所以可能会有一些理解上的错误,欢迎指出来。不过按照我的这个教程做基本上应该是会成功的。我做完这个教程自己照着又做了两遍,没问题。不过也可能会因为我没注意到一些东西,或者读者的环境跟我的不一样导致读者不成功。所以我也不敢保证。感觉早晚会失效,失效了如果我没更新的话谁看到了就回复一下提醒一下别人吧。

原文地址:https://learnku.com/articles/74366

The above is the detailed content of Teach you how to use laravel-websockets to build a 'low-profile' broadcast system. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template