0

I'm sending json data to a websocketpp server with messagepack using kawanet/msgpack-lite (javascript) on the client and msgpack/msgpack-c (C++) to unpack it and nlohmann/json to parse it on the server. This goes fine.

But I'm apparently using messagepack the wrong way since I can't parse the returned data correctly.

Server:

if (jdata["type"] == "msg") {
    std::stringstream buffer;
    std::string clientmsg = jdata["data"];
    jdata["cnt"] = clientmsg.length();
    msgpack::pack(buffer, jdata.dump());
    size_t plen = buffer.tellp();
    msg->set_payload(&buffer, plen);
    m_server.send(hdl, msg);
}

Client:

reader.onload = function (e) {
    console.log("FileReader.onload(): " + reader.result);
    var decoded_message = msgpack.decode(reader.result);
}
reader.readAsText(e.data);

It fails on msgpack.decode() with

Uncaught Error: Invalid type: 0xh

When sending json as string in set_payload()

msg->set_payload(jdata.dump());

it's transmitted fine

FileReader.onload(): {"cnt":4,"data":"test","type":"msg"}
kometen
  • 6,536
  • 6
  • 41
  • 51

2 Answers2

0

The address of a std::stringstream is not a pointer to its underlying buffer.

Try: msg->set_payload(buffer.str());.

zaphoyd
  • 2,642
  • 1
  • 16
  • 22
  • I tried that but it sends the data across in cleartext so it does not appear to be serialized. – kometen Nov 05 '15 at 15:51
  • 1
    that is because you are "packing" JSON strings. jdata.dump() serializes your data to a JSON string. msgpack::pack then packs this string. There isn't really much to pack. msgpack is generally something you would use instead of JSON, not to pack JSON. – zaphoyd Nov 06 '15 at 11:37
  • Thank you. JSON is a nice format when working with javascript but may not be so ideal for C++. I have searched for ways to serialize data between javascript and C++ and messagepack looks like the preferred one. Maby I should look for a javascript library that mimics unordered_map in C++. – kometen Nov 06 '15 at 16:24
0

If it helps: nlohmann/json now supports MessagePack (and CBOR), so you now can realize your scenario completely withing nlohmann/json. See https://github.com/nlohmann/json#binary-formats-cbor-and-messagepack for examples.

Niels Lohmann
  • 2,054
  • 1
  • 24
  • 49
  • Please don't post identical answers to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, *tailor your answers to the question.* – Андрей Беньковский Jan 01 '17 at 20:47