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]
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.