I've been reading about websockets and SaaS like Pusher and Socket.io recently, while working on my Laravel chat practice application. What I don't understand is, why do we need external software to establish a websocket connection? Can't the server code like Laravel just directly establish the connection with the front-end like Vue.js? Why does it have to go through the middleman like Pusher and Socket.io? Sorry for the noob question.

推荐答案

不需要have美元.

Those pieces of software just happen to make it trivial to work with the Websocket protocol.

Remember, Laravel is an opinionated framework. This means that it will pick and choose its own libraries to abstract away these kinds of concepts for you so that you don't have to worry so much about what's going on under the hood.

基本上,您需要两个组件才能使用WebSocket:

  1. A Websocket Server
  2. A Websocket Client

Laravel不使用Websocket直接与前端通信的原因是,Laravel本身不是Websocket服务器.至少,不是真的.虽然PHP确实支持使用Websocket协议-and even some libraries to leverage it a little more nicely,但它并不像其他语言那样经常用于处理长生命周期 的进程.

取而代之的是,Laravel使用Pub/Sub functionality that Redis provides来监听通过Redis和Predis library发生的事件.之所以这样做,是因为Larvel更适合作为websocket服务器和所有连接客户端的中间人.

In this way, Laravel can both pass information up through to the Websocket server using Broadcasting Events, as well as receive event information from the Websocket server and determine if users have the ability or authorization to receive them.

If you don't want to use Pusher, there is a library that will allow you to run your own Websocket Server specifically for Laravel called Laravel Echo Server.

Under the hood, this library still uses Socket.io and Redis in order for all moving parts to communicate with each other seamlessly in a Laravel web application. The benefit here is that you won't need to worry about the number of messages being sent by the server.

The downside is that you now have to know how to manage and maintain this process on your server so that the Websocket Server will know to turn on every time you restart your server, or if a failure happens, etc.

Check out PM2 to learn more about running and maintaining server daemons.

如果您不同意Laravel关于如何处理WebSocket的观点,那么理论上您可以使用任何其他服务器端语言来处理WebSocket协议.它只需要更多关于协议本身的工作知识;如果Laravel需要使用它,您必须知道如何编写适当的Service和Provider类来处理它.

Laravel相关问答推荐

try 编写一个函数,如果产品存在,则无法删除特定类别

如何从laravel中的另一个表中获取用户名

从主类别模型 laravel 中获取子类别翻译

Laravel 9:AWS S3 检索要流式传输的视频

1 子编译中的警告(使用'stats.children:true'和'--stats-children'了解更多详细信息)

即使上传了文件,Laravel Input::hasFile('image') 也会返回 false

在 Laravel 5 中添加新配置文件不起作用

如何判断是否在laravel中设置了cookie?

Laravel Input:all() 忽略禁用的输入

Laravel 4 的 Cron 作业(job)

在 Laravel 中将 Public 添加到assets资源路径

在Lumen框架中启用会话

Filesystem.php 中的 ErrorException

如何在 laravel 中使用 GROUP_CONCAT

如何在 Laravel 中正确安装软件包?

在 Laravel 4 中使用 HTML 占位符

Laravel 如何从子域 URL 中删除api前缀

在 laravel 的自定义路径中创建模型

同一模型上的 Laravel 父/子关系

Laravel 更新后用户模型错误(用户类包含 3 个抽象方法)