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

通过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
  • 写回答

2条回答 默认 最新

  • 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
    }))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用vmmare虚拟机用sentaurus仿真的时候,调用terminal程序,输入swb指令弹出这个,打不开workbench,桌面上面的sentaurus workbench也打不开
  • ¥75 使用winspool.drv的SetPrinter设置打印机失败
  • ¥15 simulink 硬件在环路仿真
  • ¥15 python动态规划:N根火柴摆出的最大数字
  • ¥20 (标签-excel)
  • ¥200 求idea10和MyEclipse7.1
  • ¥20 vb6.0截取当前窗体保存为jpg文件
  • ¥20 苹果手机不使用大疆sdk怎么获取遥控器控制信息或如何接入大疆sdk并且成功上架sdk
  • ¥20 woocommerce 注册按键重定向
  • ¥100 求书法图像文字切割代码