Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an array from websocket to clients

I'm having an issue sending an array from the backend js to the client side.

I've tried the following on the server side:

for (var i=0; i < clients.length; i++) {
    clients[i].send(clients);
}

for (var i=0; i < clients.length; i++) {
    clients[i].send(JSON.stringify(clients));
}
  • also using json.stringify on the client side aswell

for (var i=0; i < clients.length; i++) {
    clients[i].send(clients.join('\n')));
}
  • again I've tried this method on the client side aswell.

Unfortunately, none of the above solutions worked, The JSON.stringify method obviously didn't work on the serverside due to JSON.stringify being a browser method however the other methods returned either [object Object] or "[object Object]"

How can I send the array clients to client side, or even if I can encode it into JSON and then send it over and parse it on the client side.

Really all I need is to send the contents over to the client side, but I have no clue how to do so haha

Any ideas are appreciated :)

like image 947
Michael Zaporozhets Avatar asked May 20 '12 05:05

Michael Zaporozhets


2 Answers

If you are using Nodejs, then the JSON object is available by default (it is built into V8 so Nodejs gets it for free).

The inverse of the JSON.stringify() method is JSON.parse().

For example:

> s = JSON.stringify([1,2,3]);
'[1,2,3]'
> a = JSON.parse(s);
[ 1, 2, 3 ]

If the server is sending the result of stringify, then the client must run parse to extract the original data and vice versa.

like image 110
kanaka Avatar answered Nov 14 '22 02:11

kanaka


Although this isn't a real solution it is working for me for now unless I find a better way to do it.

Using the .toString() method:

    for (var i=0; i < clients.length; i++) {
      clients[i].send(clients.toString());
    }

and then interpreting that output on the client side with this

var clients = string.split(',');

like image 39
Michael Zaporozhets Avatar answered Nov 14 '22 01:11

Michael Zaporozhets