首页 > 解决方案 > 如何使用 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>

标签: laravelsocketswebsocketsocket.iolaravel-events

解决方案


据我了解,除了制作自处理器/处理程序之外,没有一种方法。我想,你需要看一些像 Ratchet 这样的东西。本机 laravel 构建没有处理消息的方法。有广播系统。

您使用 ajax 从客户端发送数据,然后 laravel 使用广播向所有订阅的客户端发送数据


推荐阅读