I got a webapplication written in Laravel 4. This application makes use of Ratchet and to be more specific, it uses the package Latchet. As a sidenote I am using the following techniques :
Now I got the following scenario:
In my routes.php, I have the following code, so that a topic is registered correctly :
//routes.php
// Setup a connection and register a topic where clients can connect to.
Latchet::connection('Connection');
Latchet::topic('PhotoStream/{client}', 'PhotoStreamController');
Then, I start the ratchet server.
sudo php artisan latchet:listen
When a photo gets uploaded, I can then run the following code to push updates to the clients that are listening to my topic (PhotoStream/client1
in this case):
// 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() ));
This code all works, but it is in case of an update. My question is as follows:
How should I handle the initialisation of the client?
The latter of the two options seems the best option to me but I don't really know how to implement this in a good way.
Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.
The biggest downside to using WebSocket is the weight of the protocol and the hardware requirements that it brings with it. WebSocket requires a TCP implementation, which may or may not be a problem, but it also requires an HTTP implementation for the initial connection setup.
Websockets are largely obsolete because nowadays, if you create a HTTP/2 fetch request, any existing keepalive connection to that server is used, so the overhead that pre-HTTP/2 XHR connections needed is lost and with it the advantage of Websockets.
A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript.
On the javascript side (to retrieve initial list):
//session.subscribe(....) session.call('route/to/controller', arg1, arg2).then(function(res) { console.log(res) //initial collection of photos });
On the php side (to retrieve initial list):
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)); });
Since you already successfully gotten updates via the subscribe, this is all you need. Watch out for xss though, params might not be filtred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With