使用websockets时的最佳做法?

Jac*_*tra 28 zeromq phpwebsocket laravel ratchet laravel-4

我得到了一个用Laravel 4编写的web应用程序.这个应用程序使用了Ratchet,更具体地说,它使用了Latchet软件包.作为旁注,我使用以下技术:

现在我得到以下场景:

  • 我有一个幻灯片,它应该通过websocket接收更新.
  • 整个应用程序已设置完毕,我可以通过ZeroMq将新的代码更改从PHP发布到我的websocket客户端.
  • 在我的routes.php中,我有以下代码,以便正确注册主题:

    //routes.php
    // Setup a connection and register a topic where clients can connect to.
    Latchet::connection('Connection');
    Latchet::topic('PhotoStream/{client}', 'PhotoStreamController');
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后,我启动棘轮服务器.

sudo php artisan latchet:listen

当照片上传后,我可以运行以下代码将更新推送到正在收听我主题的客户端(PhotoStream/client1在本例中):

// Create the object, save it to db and then publish it to my websockets
$photo = new Photo;
$photo->location = 'path/to/file';
$photo->save();
// Publish it through my websocket clients. (push from server).
Latchet::publish('PhotoStream/client1', array('msg' => $photo->toArray() ));
Run Code Online (Sandbox Code Playgroud)

这段代码都有效,但是在更新的情况下.我的问题如下:

我该如何处理客户端的初始化?

  1. 我应该首先使用普通的旧PHP呈现页面,然后初始化我的websocket客户端,然后接收进一步的更新(如果有的话)?
  2. 或者我应该在注册新的websocket客户端时,为请求提供额外的参数,以便服务器通过websockets向我发送完整的数据?

这两个选项中的后一个对我来说似乎是最好的选择,但我真的不知道如何以一种好的方式实现它.

Eel*_*Bos 5

在javascript端(检索初始列表):

//session.subscribe(....)

session.call('route/to/controller', arg1, arg2).then(function(res) {
   console.log(res) //initial collection of photos
});
Run Code Online (Sandbox Code Playgroud)

在php端(检索初始列表):

public function call($connection, $id, $topic, $params) {
    //the id is needed to be able to trace your async calls back to the right promise
    $connection->callResult($id, $this->getInitialPhotosFilteredByParams($params));
});
Run Code Online (Sandbox Code Playgroud)

由于您已通过订阅成功获得更新,因此这就是您所需要的.注意xss,params可能不会被过滤掉.