zsd
zsd

Reputation: 443

Socket.io how to send JavaScript object

How to send JavaScript Object with Socket.io from server to client? I'm using Socket.io as WebSocket(sending with .send() and listen with message event). When I'm trying to do something like on server-side:

var myObject = {
    message: 'Hello World!'
}

socket.send(myObject);

on client-side I'm getting only this String: [object Object]

Upvotes: 44

Views: 98609

Answers (5)

zahra_oveyedzade
zahra_oveyedzade

Reputation: 1210

In socket.io V4.x, there is no need to use JSON.stringify():

There is no need to run JSON.stringify() on objects as it will be done for you.

e.g.

// BAD
socket.emit("hello", JSON.stringify({ name: "John" }));

// GOOD
socket.emit("hello", { name: "John" });

more info on this link.

Upvotes: 4

Salman
Salman

Reputation: 82

Try using this on your server-side

socket.json.send({ your : 'data' });

and the JSON.parse() method on your client-side.

Upvotes: 5

Amro
Amro

Reputation: 124563

I just ran into this issue using some older example. Here is the answer I found: Migrating 0.6 to 0.7+, which I reproduce below.


In v0.6, socket.send would automatically convert an object like {a: 'b'} to JSON. You would send data to a client with:

socket.send({a: 'b'});

While this is cool, it poses a fundamental problem. JSON not only encodes objects, but also strings, numbers, etc! So, the API is more clear if you explicitly state you want to pass JSON (since there's a performance penalty associated with encoding/decoding JSON).

In v0.7, use the json flag:

socket.json.send({a: 'b'});

Now you can also emit and receive custom events between the browser and server:

socket.emit('my_event', {a: 'b'});

Arguments for events get encoded in JSON automatically for you.

Upvotes: 11

SaliproPham
SaliproPham

Reputation: 163

socket.send() doesn't understand object but it enjoys with JSON. You can use this way:

socket.send(JSON.stringify(myObject));

And use JSON.parse(json) to parse JSON to Object.

Upvotes: 9

Brad
Brad

Reputation: 163232

You actually need to emit an event instead:

 socket.emit('yourEvent', myObject);

If you use .send(), you are simply sending the string representation of your object, which is where the problem is occurring. Note that you can use .send(), but you would have to JSON-encode the object first, and decode it on reception.

Unless you have a specific reason, it's best to use the standard Socket.IO .emit() method, as it does all of this for you. That's what it is there for.

Upvotes: 69

Related Questions