【问题标题】:net.Dial always returns error when compile target wasmnet.Dial 在编译目标 wasm 时总是返回错误
【发布时间】:2019-08-30 18:24:03
【问题描述】:

我正在 golang 中设置一个 tcp 客户端,连接到 nodejs 中的服务器。 golang 客户端正在编译为 webassembly (wasm),并通过来自 npm 的 http-server 命令提供服务。

该程序在编译 go run main.go 时运行良好,但不适用于 wasm。如果我从场景中取出 net.dial(...) 函数,它仍然有效。

main.go连接的nodejs编写的服务器

//server.js
const net = require('net');
const port = 8081;
const host = '127.0.0.1';

const server = net.createServer();
server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port + '.');
});

let sockets = [];

server.on('connection', function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + 
sock.remotePort);
    sockets.push(sock);

    sock.on('data', function(data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        let cmp = Buffer.compare(data, Buffer.from('Connect\n'));
        // Write the data back to all the connected, the client 
will receive it as data from the server
        sockets.forEach(function(s, index, array) {
            if (cmp != 0 && s!= sock) {
                console.log('send data to ' + s.remotePort + ': ' + 
 data);
                 s.write(data+'\n');
                 // s.write(s.remoteAddress + ':' + s.remotePort + 
 " said " + data + '\n');
            }
        });
     });
});

在几种情况下都可以正常工作。 最小的 golang 代码:

//main.go
func main() {
    c := make(chan struct{}, 0)
    // ERROR HAPPENS HERE
    _, err := net.Dial("tcp", "127.0.0.1:8081")
    // -------------------------
    if err != nil {
        fmt.Println(err)
    }
    <-c
}

这是作为 wasm 运行时它在浏览器控制台上输出的内容: dial tcp 127.0.0.1:8081: Connection refused

如果正常 go run main.go 这是 server.js 上的输出: CONNECTED: 127.0.0.1:50577 表示连接成功。

【问题讨论】:

    标签: go tcp webassembly


    【解决方案1】:

    这种行为的原因是出于安全原因,wasm 编译的二进制文件是在沙盒环境中执行的,因此不支持 tcp\udp 套接字。但是,您尝试使用 websocket 来模拟所需的行为。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2018-12-28
    • 2016-04-10
    • 1970-01-01
    • 2015-12-19
    • 2012-02-26
    相关资源
    最近更新 更多