Search code examples
javascriptphpwebsocketratchet

How to send an array of objects through a single websocket send request with ratchet?


For example, currently I have to loop over each object and Stringify the object parameters, sending a separate message for every object in the array. This makes the process really slow, and causes some sync problems between users. How can I stringify and send all my objects at once and parse the result?

Client is javascript and the server uses ratchet for php.

   for (let i = circles.length - 1; i >= 0; i--) {

                if (connected) {
                    websocket_server.send(
                        JSON.stringify({
                            'type': 'circleData',
                            'user_id': circles[i].user,
                            'i': i,
                            'x': circles[i].x,
                            'y': circles[i].y,
                            'r': circles[i].r,
                            'c': circles[i].c,
                        })
                    );
                }

            }

Solution

  • Nevermind, I'm an idiot. Just stringify the object array. When it comes out the other end it will be an array of the objects, but it will not be associated with the class anymore. So, you need to use the object array data to rebuild the objects when received in order to use object methods. If anyone has a better way to associate the data with the class besides recreating the objects, let me know.

     websocket_server.send(     JSON.stringify({
                                'type': 'circleData',    
                                'obj_array': circles,
                                })
                          );
    

    Edit:

    This solution to reassign the class prototype should work:

    Re-associating an object with its class after deserialization in Node.js