gpt4 book ai didi

go - 由 golang 生成的基于 WebAssembly 的 Websockets?

转载 作者:IT王子 更新时间:2023-10-29 01:37:37 27 4
gpt4 key购买 nike

是否可以在 wasm over go 中编写 Websocket 客户端?我试过使用 gorilla/websocket,但没有成功:

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() 时出现以下错误:

dial tcp: Protocol not available

最佳答案

我通过从全局 JavaScript 对象中检索 WebSocket 对象来解决它,在我的例子中是 window 因为我正在运行它在浏览器中。我只使用了“syscall/js”库。它看起来像这样:

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
}))

关于go - 由 golang 生成的基于 WebAssembly 的 Websockets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com