由 golang 生成的 WebAssembly 上的 Websockets? [英] Websockets over WebAssembly generated by golang?
本文介绍了由 golang 生成的 WebAssembly 上的 Websockets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 wasm over go 中编写 Websocket 客户端?我曾尝试使用 gorilla/websocket
,但没有成功:
Is it possible to write a Websocket client in wasm over go? I have tried using gorilla/websocket
, but no success:
func main() {
ws := func(this js.Value, inputs []js.Value) interface{} {
go func() {
wsDial, r, err := websocket.DefaultDialer.Dial("ws://localhost:3000/ws", nil)
fmt.Println(wsDial, r, err)
}()
return nil
}
js.Global().Set("ws", js.FuncOf(ws))
select {}
}
调用 ws()
时出现以下错误:
I get the following error when calling ws()
:
dial tcp: Protocol not available
推荐答案
我通过从全局 JavaScript
对象中检索 WebSocket
对象解决了这个问题,在我的例子中是 window
因为我在浏览器中运行它.我只使用了syscall/js"库.它看起来像这样:
I have solved it by retrieving the WebSocket
object from the global JavaScript
object, which in my case is window
because I am running this in a browser. I have used only the "syscall/js" library. It looks like this:
ws := js.Global().Get("WebSocket").New("ws://localhost:8080/ws")
ws.Call("addEventListener", "open", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
fmt.Println("open")
ws.Call("send", js.TypedArrayOf([]byte{123}))
return nil
}))
这篇关于由 golang 生成的 WebAssembly 上的 Websockets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文