本文介绍了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