socket.io - 来自服务器的已发出对象在客户端收到后会丢失其功能和名称 [英] socket.io - emited objects from server lose their functions and name once received by client

查看:99
本文介绍了socket.io - 来自服务器的已发出对象在客户端收到后会丢失其功能和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦玩家连接,服务器就会发出一条名为playerNumber的消息,其中包含所有玩家的数据(玩家存储在对象中,所有这些对象都存储在一个名为allPlayers的数组中),以及他们的玩家编号。



一旦客户收到此消息,对象就会神秘地丢失其名称(Blob现在称为对象)并且他们也失去了所有功能。 / p>

为什么会发生这种情况的任何想法?

解决方案

我们需要查看你的ACTUAL代码,以便建议解决这个问题的具体代码。



一般来说,你必须自己序列化一个对象(到一个字符串)然后通过套接字发送它.IO。 Javascript无法通过TCP将活动对象发送到另一台计算机。相反,您必须创建对象的二进制或字符串表示,然后发送它,然后在接收端,您从序列化表示重建所需的对象。 Javascript没有自动执行此操作的内置机制。



常用的一个工具是 JSON.stringify() JSON.parse() JSON.stringify()将采用普通对象并序列化字符串中的可枚举属性。 JSON.parse()将采用序列化的JSON字符串并将其解析回普通对象。



但是,如果你的对象是某种带有自定义方法的自定义对象,那么你必须自己添加那部分重建,因为对象JSON方法只处理普通对象。通常,我在这种情况下所做的是我不会尝试序列化整个对象。相反,我确定需要将哪些确切的数据发送到另一个主机,将其添加到某个字符串形式,发送,在另一端解析,创建所需类型的对象,然后使用发送。


Once the player connects, the server emits a message called "playerNumber" which carries the data of all players (players are stored in objects, and all those objects are stored into an array called "allPlayers"), and their player numbers.

Once this is received by the client, the objects mysteriously lose their name ("Blob" now is called "Object") and they lose all their functions too.

Any ideas to why this has happened?

解决方案

We would need to see your ACTUAL code in order to suggest specific code to solve this problem.

Generically, you have to serialize an object yourself (into a string) before sending it over socket.io. Javascript can't send live objects over TCP to another computer. Instead, you have to create a binary or string representation of the object, then send that, then on the receiving end you reconstruct the desired object from the serialized representation. Javascript does not have a built-in mechanism for doing this automatically.

One tool that is commonly used is JSON.stringify() and JSON.parse(). JSON.stringify() will take a plain object and serialize the enumerable properties in a string. JSON.parse() will take a serialized JSON string and parse it back into a plain object.

But, if your object is some sort of custom object with custom methods, then you will have to add that part of the reconstruction yourself because the object JSON methods only handle plain objects. Usually, what I do in this case is I don't attempt to serialize the whole object. Instead, I determine what exact pieces of data need to be sent to the other host, extra those into some string form, send that, parse that on the other end, create the desired type of object and then initialize it with the data that was sent.

这篇关于socket.io - 来自服务器的已发出对象在客户端收到后会丢失其功能和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆