Golang插座IO无法建立WebSocket连接
这是我的插座IO GO服务器,基本上是按照 package 的示例代码:
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>
我的客户端只需继续发送长插图获取请求,无法建立Websocket连接。我怀疑这可能与我的服务器响应有关吗?从浏览器DevTool中,似乎我在响应有效载荷前面有一些随机字节:
我无法解决问题。任何帮助将不胜感激,谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用客户端的4.5.0版本以及(我假设 - 请)
github.com/googollee/go-socket.io
。 go package package readme 状态:socket io docs 提供兼容性图表,显示服务器的V1是仅由客户端版本1支持。因此以下似乎有效( playground> playground - 注意,我也做出了细微的更改):
要使用后期版本的socket.io,您将需要一个支持该协议后期版本的服务器。 gosf 似乎支持V2,但我没有尝试过。
You are using version 4.5.0 of the client along with (I assume - minimal reproducable examples please)
github.com/googollee/go-socket.io
. The go package readme states:The socket io docs provide a compatibility chart showing that v1 of the server is only supported by version 1 of the client. So the following appears to work (playground - note I also made subtle changes so the message is output):
To use a later version of Socket.IO you will need a server that supports a later version of the protocol. gosf appears to support v2 but I have not tried it.