我的桌面上运行着一个 python 服务器,它解析一个大的 CSV 文件,并将每一行发送到嵌入式设备,以响应 HTTP 请求作为 cjson 文件设置,就像这样,当我在同一设备上测试它时,可以很好地接收它一个 C 程序,但当我尝试在嵌入式 Linux ubuntu 设备上运行相同的代码时失败。代码编译并且所有数据都从服务器正确发送,但收到的数据随机丢失值会出现问题
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header('Content-Encoding', 'chunked') # Specify gzip encoding
self.end_headers()
response_data = self.read_csv_lines(param_value)
response_json = json.dumps(response_data)
# Compress the JSON data
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode='w') as f:
f.write(response_json.encode('utf-8'))
compressed_data = buf.getvalue()
# Send the compressed JSON response
self.wfile.write(compressed_data)
这是我的 C 代码,用于发送响应以及处理传入数据。
'''
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
char *data = (char *)userp;
// Append the received data to the user buffer
memcpy(data, curl_buffer, realsize);
return realsize;
}
void readDatasetLineByLine(CURL* curl ,CURLcode res ,int line_number){
// Read float values from file
float value;
char url_query[50];
sprintf(url_query,"http://192.168.137.1:8080?param=%d",line_number);
curl_easy_setopt(curl, CURLOPT_URL, url_query);
// Set the callback function to handle received data
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
// Create a buffer to store the received data
// Perform the HTTP request
res = curl_easy_perform(curl);
test_input_memory[0] = value;
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
// Print the received text
cJSON *root = cJSON_Parse(curl_buffer);
if (root != NULL) {
// Check if the root is an array
if (cJSON_IsArray(root)) {
// Iterate through the array and print the float values
int count = 0;
cJSON *value;
cJSON_ArrayForEach(value, root) {
if (cJSON_IsNumber(value)) {
test_input_memory[count] = (float)value->valuedouble;
count += 1;
}
}
}
// Free cJSON objects
cJSON_Delete(root);
}
else
{
fprintf(stderr, "Error parsing JSON\n");
}
}
我发现最好奇的是 write_callback 函数运行多次,随机分割一些响应,但以一种没有显示明显模式的方式保留其他响应。如何复制整个响应而不出现任何错误或缺失值?
我设法解决了这个问题,问题是我的 write_callback 函数不支持由同一响应多次调用,因为我不知道这种行为是可能的。通过修改它以跟踪资源分解为多个交互时的偏移量,无论 lib-curl 如何分割每个请求,我都能够保持代码正常工作。