這是我的 socket io Go 服務(wù)器,基本上遵循包的示例代碼:func main() { server := socketio.NewServer(nil) server.OnConnect("/", func(s socketio.Conn) error { s.SetContext("") fmt.Println("connected:", s.ID()) return nil }) server.OnEvent("/", "notice", func(s socketio.Conn, msg string) { fmt.Println("notice:", msg) s.Emit("reply", "have "+msg) }) server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string { s.SetContext(msg) return "recv " + msg }) server.OnEvent("/", "bye", func(s socketio.Conn) string { last := s.Context().(string) s.Emit("bye", last) s.Close() return last }) server.OnError("/", func(s socketio.Conn, e error) { fmt.Println("meet error:", e) }) server.OnDisconnect("/", func(s socketio.Conn, reason string) { fmt.Println("closed", reason) }) go server.Serve() defer server.Close() mux := http.NewServeMux() mux.Handle("/socket.io/", server) // socket io log.Println("Serving at localhost:8000...") log.Fatal(http.ListenAndServe(":8000", cors.Default().Handler(mux)))}這是我的客戶端代碼:<script src="https://cdn.socket.io/4.5.0/socket.io.min.js" integrity="sha384-7EyYLQZgWBi67fBtVxw60/OWl1kjsfrPFcaU0pp0nAh+i8FD068QogUvg85Ewy1k" crossorigin="anonymous"></script><script> const socket = io("http://localhost:8000"); socket.emit("msg", "abc")</script>我的客戶端一直在發(fā)送長輪詢 GET 請求,無法建立 websocket 連接。我懷疑這可能與我的服務(wù)器響應(yīng)有關(guān)?從瀏覽器開發(fā)工具來看,我的響應(yīng)負(fù)載前面似乎有一些隨機(jī)字節(jié):
Golang socket io無法建立websocket連接
繁華開滿天機(jī)
2022-12-19 21:20:21