wasm二进制文件与在终端中运行的二进制文件相比,输出结果不正确。

huangapple go评论70阅读模式
英文:

wasm binary giving wrong output as compared to running binary in terminal

问题

我有一个 Go 程序(https://github.com/klauspost/cpuid),我在终端中运行它,它完全正常工作。

我想把它变成在浏览器中运行的服务。我唯一能想到的方法是将其编译为 wasm 二进制文件并静态地提供该文件。

但问题是,终端和浏览器中的输出是不同的。我在这里有什么遗漏吗?

  1. Go 代码在上面共享的存储库中可用。
  2. 使用 GOOS=js GOARCH=wasm go build -o test.wasm test.go 将程序编译为 wasm。
  3. 用于静态提供文件的 JavaScript 代码:
const http = require('http');
const nStatic = require('node-static');

// wasm 文件位于 public 文件夹中。
// 使用的是 go 安装中提供的 wasm_exec.js
const fileServer = new nStatic.Server('./public');

const PORT = 8000;

http.createServer(function (req, res) {
  fileServer.serve(req, res);
}).listen(PORT);

在浏览器中的效果:链接

在终端中的效果:链接

英文:

I have a go program (https://github.com/klauspost/cpuid) which I'm running in my terminal and it works perfectly fine.
I wanted to make it like a service running in browser. The only way possible I see is to compile it to wasm binary and serve the file statically.

But the problem is, output in terminal and browser are different. Anything I'm missing here?

  1. go code is available in repo shared above
  2. programm is compiled to wasm using GOOS=js GOARCH=wasm go build -o test.wasm test.go
  3. Js code to serve statically
const http = require('http');

const nStatic = require('node-static');

// wasm file is in public folder. 
// wasm_exec.js is used which is available in go installtion
const fileServer = new nStatic.Server('./public');

const PORT = 8000;

http.createServer(function (req, res) {

  fileServer.serve(req, res);

}).listen(PORT);

In browser

In terminal

答案1

得分: 2

在技术上来说,尽管最终两者都在同一CPU上运行,但它们并不完全相同。WASM是一种用于虚拟CPU的字节码。大多数浏览器会将该字节码转换为机器字节码,然后执行。但是,它确保从这个虚拟机器几乎无法访问真实机器,除非经过授权的API。因此,无论是哪个函数,它们很可能会失败,或者被替换为虚拟函数,并返回错误代码或虚拟值,这些值被选择为与真实值区分开来。

英文:

While in the end both is run on the same the CPU that is not true technically. WASM is bytecode for an Virtual CPU. That bytecode is translated into machine bytecode by most browsers and then executed. But it secured that from this virtual machine nearly no access can be made to the real machine except he accepted API. So whatever functions they will most likely fall or where replaced by dummy functions and so on return error codes or dummy values that where chosen in a way they can be distinguished from real values.

huangapple
  • 本文由 发表于 2022年5月31日 21:39:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/72448888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定