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.

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?