c - 是否可以使用 WebAssembly 提交 HTTP 请求?

标签 c http xmlhttprequest emscripten webassembly

我正在尝试在 WebAssembly 中提交一个简单的 HTTP GET 请求。为此,我编写了这个程序(从 Emscripten site 复制并稍作修改):

#include <stdio.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/fetch.h>
#include <emscripten.h>
#endif


void downloadSucceeded(emscripten_fetch_t *fetch) {
  printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
  // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1];
  emscripten_fetch_close(fetch); // Free data associated with the fetch.
}

void downloadFailed(emscripten_fetch_t *fetch) {
  printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status);
  emscripten_fetch_close(fetch); // Also free data on failure.
}

unsigned int EMSCRIPTEN_KEEPALIVE GetRequest() {
  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);
  strcpy(attr.requestMethod, "GET");
  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
  attr.onsuccess = downloadSucceeded;
  attr.onerror = downloadFailed;
  emscripten_fetch(&attr, "http://google.com");
  return 1;
}

当我使用 $EMSCRIPTEN/emcc main.c -O1 -s MODULARIZE=1 -s WASM=1 -o main.js --emrun -s FETCH=1 编译它时,我得到了错误

ERROR:root:FETCH not yet compatible with wasm (shared.make_fetch_worker is asm.js-specific)

有没有办法从 WebAssembly 运行 HTTP 请求?如果是,我该怎么做?

更新 1:以下代码尝试发送 GET 请求,但由于 CORS 问题而失败。

#include <stdio.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/fetch.h>
#include <emscripten.h>
#endif

unsigned int EMSCRIPTEN_KEEPALIVE GetRequest() {
  EM_ASM({
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://google.com");
    xhr.send();
  });
  return 1;
}

最佳答案

不,您不能从 WebAssembly 执行 HTTP 请求(或访问 DOM,或任何其他浏览器 API)。 WebAssembly 本身无法访问其宿主环境,因此它没有任何内置的 IO 功能。

但是,您可以从 WebAssembly 导出函数,并从主机环境导入函数。这将允许您通过主机间接发出 HTTP 请求。

关于c - 是否可以使用 WebAssembly 提交 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102612/

相关文章:

javascript - Promise 本身是否有一个时间,如果在特定的时间内从未解决,它最终会是 `reject` 本身吗?

javascript - 使用 xmlhttprequest 读取文件导致错误控制台条目

c - 为什么不能定义大于300*300的二维数组?

c - 在STM32F407中断处理程序中禁用中断

angular - 如何在 Angular 6 同步运行的第一个订阅中使用第二个订阅返回值?

regex - 允许特定文件通过 https 运行

javascript - 如何使用 javascript 中的 http.post 将图像发送到服务器并在 mongodb 中存储 base64

c - 不同类型和大小的指针的 union

c - 家庭作业,卡在指针和函数调用上

ios - 在同一个 POST 中发送 NSData 和 NSString