socket.io - emited objects from server lose their functions and name once received by client

后端 未结 1 898
失恋的感觉
失恋的感觉 2021-01-24 23:00

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 stor

相关标签:
1条回答
  • 2021-01-24 23:39

    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.

    0 讨论(0)
提交回复
热议问题