title: Parsing variable-sized packets
body: <p>I'm working on a multiplayer game and I'm having an issue with the the way I parse the packets from the connection. When I'm debugging the game it runs at a lower performance and the packets are received, when I'm not, packets aren't fully received and the ParsePacket method isn't called.</p>
  
  <p>My packet structure is this:</p>
  
  <blockquote>
    <p>2 Bytes Short Command, 2 Bytes Short Payload Size, (Optional) Payload Bytes</p>
  </blockquote>
  
  <pre><code>IInputStream inputStream = null;
  DataReader dataReader = null;
  
  byte[] data = new byte[1024];
  IBuffer buffer = data.AsBuffer();
  
  try
  {
      inputStream = StreamSocket.InputStream;
  
      dataReader = DataReader.FromBuffer(buffer);
      dataReader.InputStreamOptions = InputStreamOptions.Partial;
      dataReader.ByteOrder = ByteOrder.LittleEndian;
  
      while (connected)
      {
          await inputStream.ReadAsync(buffer, 1024, InputStreamOptions.Partial);
          Debug.WriteLine("Buffer " + buffer.Length);
  
          if (buffer.Length &gt;= PacketHeaderSize)
          {
              short command = dataReader.ReadInt16();
              short payloadSize = dataReader.ReadInt16();
              byte[] payload = null;
  
              if (payloadSize == 0)
              {
                  UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));
  
                  Packet packet = new Packet(command, payloadSize, payload);
                  ParsePacket(packet);
              }
              else if (payloadSize &gt; 0)
              {
                  if (buffer.Length &gt;= (PacketHeaderSize + payloadSize))
                  {
                      payload = new byte[payloadSize];
                      dataReader.ReadBytes(payload);
  
                      UpdateBuffer(buffer, (uint)(PacketHeaderSize + payloadSize));
  
                      Packet packet = new Packet(command, payloadSize, payload);
                      ParsePacket(packet);
                  }
              }
          }
      }
  }
  catch (Exception e) {
      // ...
  }
  
  private void UpdateBuffer(IBuffer buffer, uint bytesRead)
  {
      if (buffer.Length &gt; bytesRead)
      {
          byte[] bufferBytes = new byte[buffer.Length - bytesRead];
          System.Buffer.BlockCopy(buffer.ToArray(), (int)bytesRead, bufferBytes, 0, (int)(buffer.Length - bytesRead));
          buffer = bufferBytes.AsBuffer();
      }
      else
      {
          byte[] bufferBytes = new byte[1024];
          buffer = bufferBytes.AsBuffer();
      }
  }
  </code></pre>
  
  <p>What I'm doing wrong?</p>