这是我的 socket io Go 服务器,基本上遵循包的示例代码:
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>
我的客户端一直在发送长轮询 GET 请求,无法建立 websocket 连接。我怀疑这可能与我的服务器响应有关?从浏览器开发工具来看,我的响应负载前面似乎有一些随机字节:
猛跑小猪
相关分类