Go 编译目标wasm时,拨号总是返回错误
我正在golang设置一个tcp客户端,连接到nodejs中的服务器。golang客户端正在编译为webassembly(wasm),并由npm通过http服务器命令提供服务 该程序在编译时运行良好,但不能与wasm一起使用。不过,如果我从场景中取出Go 编译目标wasm时,拨号总是返回错误,go,tcp,webassembly,Go,Tcp,Webassembly,我正在golang设置一个tcp客户端,连接到nodejs中的服务器。golang客户端正在编译为webassembly(wasm),并由npm通过http服务器命令提供服务 该程序在编译时运行良好,但不能与wasm一起使用。不过,如果我从场景中取出net.dial(…)函数,它就会工作 用nodejs编写的服务器,main.go在其中连接到 //server.js const net = require('net'); const port = 8081; const host = '127.
net.dial(…)
函数,它就会工作
用nodejs编写的服务器,main.go在其中连接到
//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
}
//main.go
func main(){
c:=make(chan结构{},0)
//这里发生了错误
_,err:=net.Dial(“tcp”,“127.0.0.1:8081”)
// -------------------------
如果错误!=零{
fmt.Println(错误)
}
这种行为的原因是,出于安全考虑,wasm编译的二进制文件是在沙箱环境中执行的,因此不支持tcp\udp套接字。但是,您试图通过使用websocket来模拟所需的行为。我希望websocket在wasm上实现,我会尝试。是的,websocket是可用的。她e就是这样一个例子