socket.io-unity icon indicating copy to clipboard operation
socket.io-unity copied to clipboard

How to pass JSON data consisting of key/value pairs to the emit function?

Open BlurEffect opened this issue 5 years ago • 3 comments

Hey guys,

this project seems to be exactly what I need but I'm having an issue that prevents me from being able to use it properly. I'm pretty sure it's less than an issue and more a misunderstanding of how to use it properly but I didn't find any way to write a comment or contact the author directly, so I'm opening up an issue for it in the hope someone can point me towards a solution. Thing is, I want to emit messages through the sockets with an already properly formatted JSON string as data. Since the emit function takes an array of type object I assumed I could just pass my JSON string and it would be fine. Turns out, however, that the string is modified internally within the emit function and I'm pretty sure that's why I'm not able to properly communicate with my server.

The string I'm passing in as data for my message: "{\"name\":\"SomeName\",\"type\":\"SomeType\",\"value\":\"SomeValue\"}"

What the emit function turns it into before sending it off: \"{\\\"name\\\":\\\"SomeName\\\",\\\"type\\\":\\\"SomeType\\\",\\\"value\\\":\\\"SomeValue\\\"}\"

I would like to know how I can pass an already formatted JSON without it being modified internally or alternatively I would like to hear how I can pass in data as shown above using the objects[] Parameter of the emit function. The example code only shows how to pass a single bit of data.

Thank you very much in Advance for your help. Kind Regards

BlurEffect avatar Aug 06 '20 07:08 BlurEffect

hi there

I understand that you want to send JSON string. I've done an experiment, and it's as follows.

  1. c# unity code image

  2. nodejs server code image

  3. unity log image

  4. nodejs log image

The json string was delivered normally.

Was there anything I misunderstood in your question? I am not a native speaker of English, so I may need a detailed explanation.

Rocher0724 avatar Aug 07 '20 02:08 Rocher0724

Not the best solution. But you can parse the string that comes to your server

image

So you will be able to process and valid string and object

Shinken44 avatar Nov 09 '20 14:11 Shinken44

For me I send directly Json through socket. Csharp/Unity side:

JObject data = new JObject();
data["name"]="engine";
socket.Emit("Register",data);

On nodeJS side:

  socket.on("Register", (data) => {
      console.log("Data name:"+data.name)
      clients[data.name]=socketId;
      clientName=data.name;
});

No need for parsing. Direct json exchange.

hachpai avatar Dec 27 '20 14:12 hachpai