title: send a json containing a big buffer (bytearray) through sockets: gets truncated
body: <p>I'm trying to send a json containing text fields and a buffer in a bytearray, from a micro-controller to a Windows server</p>
  <pre class="lang-py prettyprint-override"><code>msg = {&quot;some_stuff&quot;: &quot;some_stuff&quot;, &quot;buf&quot;: bytearray(b'\xfe\xc2\xf1\xfe\xd5\xc0 ...')}
  </code></pre>
  <p>Note that <strong>the buffer is quite long</strong> (so that I can't put it here as reference) <code>len(buf) -&gt; 35973</code></p>
  <p>I'm sending the length of the message before to the server so that it knows how long is the message to be received</p>
  <pre class="lang-py prettyprint-override"><code>def send_json(conn, msg):
      msg = json.dumps(msg).encode('utf-8')
      msg_length = len(msg)
      header = str(msg_length).encode('utf-8')
      header += b' ' * (64 - len(header))
      conn.send(header)
      conn.send(msg)
  </code></pre>
  <p>The receiving function is then</p>
  <pre class="lang-py prettyprint-override"><code>def receive_json(conn) -&gt; dict:
      msg_length = int(
          conn.recv(64).decode('utf-8').replace(' ', '')
      )
      msg_b = conn.recv(msg_length)
      msg_s = msg_b.decode('utf-8')
      try:
          msg_d = json.loads(msg_s)
      except:
          msg_d = eval(msg_s)
      return msg_d
  </code></pre>
  <p>The problem is that <strong>the received message is truncated</strong>.</p>
  <pre><code>msg_b = b'{&quot;buf&quot;: bytearray(b\'\\xfe\\xc2\\xf1 ... \\x06u\\xd0\\xff\\xb'
  </code></pre>
  <p>It's worth mentioning that while in debug, if I stop for a while with a breakpoint on line <code>msg_b = conn.recv(msg_length)</code>, before running it, the received message is complete.</p>
  <p>So <strong>it seems that in the receiving function the <code>conn.recv(msg_length)</code> instruction does not wait to receive a message of the specified length</strong> (<code>msg_length</code>)</p>
  <p>Why is it the case? What can I do to receive a complete message?</p>
  <p>I could introduce <code>time.sleep</code> between receiving the length of the message and the message, but how to know how much to wait depending on the message length?</p>
  <p>Thank you</p>