Rocher0724 / socket.io-unity

MIT License
107 stars 19 forks source link

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

Open BlurEffect opened 4 years ago

BlurEffect commented 4 years ago

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

Rocher0724 commented 4 years ago

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.

Shinken44 commented 3 years ago

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

hachpai commented 3 years ago

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.