Reputation: 83
this is my socket io Go server, basically following the package's example code:
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)))
}
And this is my client side code:
<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>
My client side just keep sending long-polling GET requests, the websocket connection cannot be established. I suspect it might have something to do with my server response? From the browser devtool, it seems like I have some random bytes in front of my response payload:
I wasn't able to solve the issue. Any help would be appreciated, thank you!
Upvotes: 1
Views: 2226
Reputation: 18290
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:
Current this library supports 1.4 version of the Socket.IO client. It supports room, namespaces and broadcast at now.
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):
<script src="https://cdn.socket.io/socket.io-1.7.4.min.js"></script>
<script>
const socket = io("http://localhost:8000");
socket.emit("msg", "abc");
</script>
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.
Upvotes: 1