sundq
sundq

Reputation: 763

tornado websocket get multi message when on_message called

I use tornado websocket send/recv message, the client send json message, and server recv message and json parse, but why the server get message which is mutil json message, such as {"a":"v"}{"a":"c"}, how to process this message

Upvotes: 0

Views: 287

Answers (2)

sundq
sundq

Reputation: 763

I write a fucntion to parse this message

def parse_multi_msg(msg):
  is_in_quotation = False
  aObjs = []
  sTemp = ""
  for c in msg:
    sTemp += c;

    if c == '"':
      if not is_in_quotation:
        is_in_quotation = True
      else:
        is_in_quotation= False


    if c == "}" and not is_in_quotation:
      aObjs.append(json.loads(sTemp));
      sTemp = "";

  return aObjs

Upvotes: 0

Maybe you should delimit the messages you send so it is easy to split them up - in this case you could add a \n, obviously the delimiter mustn't happen within the message. Another way would be to prefix each message with its length in also a clearly-delimited way, then the receiver reads the length then that number of bytes and parses it.

Upvotes: 1

Related Questions