duanjue7745 2012-11-25 12:46
浏览 280

如何使Websocket客户端等待服务器运行?

I want to create a websocket client that waits until the server is running. If the connection is closed by the server it should reconnect.

What I tried does not work and my code exits with a runtime error:

panic: runtime error: invalid memory address or nil pointer dereference

func run() {
  origin := "http://localhost:8080/"
  url := "ws://localhost:8080/ws"

  ws, err := websocket.Dial(url, "", origin)

  if err != nil {
      fmt.Println("Connection fails, is being re-connection")
      main()
  }

  if _, err := ws.Write([]byte("something")); err != nil {
    log.Fatal(err)
  }
}
  • 写回答

1条回答 默认 最新

  • dsuoedtom207012191 2012-11-25 16:56
    关注

    Your example looks like a code snippet. It's difficult to say why you're getting that error without seeing all the code. As were pointed out in the comments to your post, you can't call main() again from your code and including the line numbers from the panic report would be helpful as well.

    Usually minimizing your program to a minimal case that anyone can run and reproduce the error is the fastest way to get help. I've reconstructed yours for you in such fashion. Hopefully you can use it to fix your own code.

    package main
    
    import (
        "websocket"
        "fmt"
        "log"
        "time"
        )
    
    func main() {
        origin := "http://localhost:8080/"
        url := "ws://localhost:8080/ws"
    
        var err error
        var ws *websocket.Conn
        for {
            ws, err = websocket.Dial(url, "", origin)
            if err != nil {
                fmt.Println("Connection fails, is being re-connection")
                time.Sleep(1*time.Second)
                continue
            }
            break
        }
        if _, err := ws.Write([]byte("something")); err != nil {
            log.Fatal(err)
        }
    
    }
    

    To run this, just copy it into a file called main.go on your system and then run:

    go run main.go
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题