我在 GoLang 上有一个服务器,并且googollee/go-socket.io
.
当服务端和客户端工作在同一个端口时,sockets正常工作。但是当我开始它们在不同的端口上时,客户端会发生错误:
WebSocket connection to 'ws://localhost:4444/socket.io/?EIO=3&transport=websocket&sid=6' failed: Error during WebSocket handshake: Unexpected response code: 403
POST http://localhost:4444/socket.io/?EIO=3&transport=polling&t=NDDzcYM&sid=5 400 (Bad Request)
GET http://localhost:4444/socket.io/?EIO=3&transport=polling&t=NDDzcYC&sid=5 400 (Bad Request)
WebSocket connection to 'ws://localhost:4444/socket.io/?EIO=3&transport=websocket&sid=5' failed: Error during WebSocket handshake: Unexpected response code: 403
在服务器上:
connected: 1 closed client namespace disconnect meet error: json: cannot unmarshal object into Go value of type string connected: 2
这是我的代码:
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
socketio "github.com/googollee/go-socket.io"
)
func main() {
fmt.Println("Hello world")
router := mux.NewRouter()
router.HandleFunc("/is-alive", isAlive).Methods("GET")
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
fmt.Println("connected:", s.ID())
s.Emit("change")
s.Join("bcast")
return nil
})
server.OnEvent("/", "msg", func(s socketio.Conn, msg string) string {
s.SetContext(msg)
s.Emit("change")
fmt.Println("event: msg")
return "recv " + msg
})
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()
router.Handle("/socket.io/", server)
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowCredentials: true,
})
handler := c.Handler(router)
log.Println("Serving at localhost:4444...")
log.Fatal(http.ListenAndServe(":4444", handler))
}
func isAlive(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
在我的反应应用程序上
import socketIOClient from "socket.io-client";
export class SocketClientManager {
public socket = socketIOClient("ws://localhost:4444");
public subscribe() {
this.socket.emit("msg", { msg: "Hello!" });
}
public setCallback(callback: (arg: any) => void) {
this.socket.on("change", callback);
}
public async unsubscribe() {
this.socket.disconnect();
}
}