【发布时间】: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