io如何发送JavaScript对象

io如何发送JavaScript对象

本文介绍了Socket.io如何发送JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Socket.io从服务器向客户端发送JavaScript对象?我使用Socket.io作为WebSocket(发送.send()发送并监听message事件).当我尝试在服务器端执行类似操作时:

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);

在客户端,我只得到以下字符串:[object Object]

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

推荐答案

实际上,您需要发出一个事件:

You actually need to emit an event instead:

 socket.emit('yourEvent', myObject);

如果使用.send(),则只是在发送对象的字符串表示形式,这就是问题所在.请注意,您可以使用.send(),但必须先对对象进行JSON编码,然后在接收时对其进行解码.

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.

除非有特殊原因,否则最好使用标准的Socket.IO .emit()方法,因为它可以为您完成所有这些工作.那就是它的用途.

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.

这篇关于Socket.io如何发送JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:22