doudui1850
doudui1850
2019-04-18 17:19
浏览 388
已采纳

通过golang在WebAssembly上的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 {}
}

I get the following error when calling ws():

dial tcp: Protocol not available

图片转代码服务由CSDN问答提供 功能建议

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

  func main(){
 ws:= func(this js.Value, 输入[] js.Value)接口{} {
 go func(){
 wsDial,r,err:= websocket.DefaultDialer.Dial(“ ws:// localhost:3000 / ws”,nil)
 fmt  .Println(wsDial,r,err)
}()
返回nil 
} 
 
 js.Global()。Set(“ ws”,js.FuncOf(ws))
 
选择{  } 
} 
   
 
 

调用 ws()时收到以下错误:

  拨号tcp:协议不可用
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanbushi1867
    duanbushi1867 2019-04-22 09:34
    已采纳

    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
    }))
    
    点赞 评论
  • duanaigua4033
    duanaigua4033 2019-04-20 13:38

    Have a look at the gopherJS websocket library. This one was created to run in the browser (originally js).

    I recently saw a youtube video with it being in use in WASM but I couldn't find it any more.

    点赞 评论

相关推荐