mahmoud fathy
mahmoud fathy

Reputation: 391

net.Dial always returns error when compile target wasm

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\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');
            }
        });
     });
});

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.

Upvotes: 1

Views: 1144

Answers (1)

Mikhail
Mikhail

Reputation: 859

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.

Upvotes: 3

Related Questions