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

huangapple go评论79阅读模式
英文:

How to make a websocket client wait util the server is running?

问题

我想创建一个WebSocket客户端,它会等待服务器运行。如果服务器关闭连接,它应该重新连接。

我尝试的方法不起作用,我的代码会出现运行时错误:

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("连接失败,正在重新连接")
    main()
  }

  if _, err := ws.Write([]byte("something")); err != nil {
    log.Fatal(err)
  }
}
英文:

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

得分: 8

你的示例看起来像一个代码片段。没有看到所有的代码,很难说你为什么会得到那个错误。正如在你的帖子的评论中指出的,你不能从你的代码中再次调用main(),包括panic报告中的行号也会有帮助。

通常,将程序最小化为任何人都可以运行和重现错误的最小情况是获得帮助的最快方法。我已经为你重建了这个程序。希望你可以用它来修复你自己的代码。

要运行这个程序,只需将它复制到名为main.go的文件中,然后运行:

go run main.go

英文:

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

huangapple
  • 本文由 发表于 2012年11月25日 20:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/13551140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定