英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论