laravel - 如何使用 socket.io 从客户端发送数据到 laravel
问题描述
我正在尝试使用 socket.io。并想从我的 javascript(客户端)发送一个变量到 laravel 事件,然后将其传递回客户端。我在我的代码中评论了我想要的。
下面是我的代码:
事件:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class MarketUpdate implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public $data;
public function __construct()
{
$this->data = [
'abcd' => $id , /// I need to get this ID from client side.
];
}
public function broadcastOn()
{
return array('channel_test');
}
}
客户端JS:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var id = '9';
var socket = io('http://localhost:8890');
socket.on("channel_test:App\\Events\\EventNew", function (message) {
// I Want to send id here somewhere and display
$('#abcd').html(message.data.abcd);
});
</script>
解决方案
据我了解,除了制作自处理器/处理程序之外,没有一种方法。我想,你需要看一些像 Ratchet 这样的东西。本机 laravel 构建没有处理消息的方法。有广播系统。
您使用 ajax 从客户端发送数据,然后 laravel 使用广播向所有订阅的客户端发送数据
推荐阅读
- c++ - C++ 合并 2 wchar_t*
- c# - 是否可以使用 switch 语句管理循环?
- php - 在 PHP 中,如何使用 cURL 从 web 目录下载多个相同类型的文件?
- reactjs - 启动 npm 服务器时出现错误
- android - 以编程方式将 strokeColor 设置为 CardView
- swift - 如何一次关闭我的 DimmingView 和 SlideMenu?
- java - 使用 setOnItemClickListener 接口时无法从 ListView 接收值
- javascript - 如何获得不包括背景的视频高度宽度
- mysql - “连接到本地服务被拒绝,因为......” Torsocks 错误 - 我如何连接到本地 Mysql 服务器?
- java - 在 Maven 存储库中找不到 SpringSecurityUser 类