douwen5985 2019-08-30 18:24
浏览 210

编译目标wasm时net.Dial始终返回错误

I am setting up a tcp client in golang connecting to a server in nodejs. The golang client is being compiled to webassembly (wasm) and served by via http-server command from npm.

The program works well when compiled go run main.go but does not work with wasm. It works though if I take out the net.dial(...) function from the scene.

The server written in nodejs in which main.go connects to

//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
'));
        // 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+'
');
                 // s.write(s.remoteAddress + ':' + s.remotePort + 
 " said " + data + '
');
            }
        });
     });
});

which works fine in several cases. The minimal golang code:

//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
}

This is what it outputs on the browser's console when run as wasm: dial tcp 127.0.0.1:8081: Connection refused

If normal go run main.go this is the output on the server.js: CONNECTED: 127.0.0.1:50577 which implies connection is successful.

  • 写回答

1条回答 默认 最新

  • douxian7534 2019-08-31 08:08
    关注

    The reason for that kind of a behaviour is that wasm compiled binaries are executed in the sandbox environment for the security reasons, so there is no support for tcp\udp sockets. However you try to emulate the desired behaviour by using websockets.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?