我需要解决golang服务器上的websocket问题



我在GoLang和googollee/go-socket.io上有一个服务器。
当服务器和客户端在同一个端口上工作时,套接字工作正常。但当我启动它们时,它们在不同的端口上,客户端出现错误:

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)
}

在我的react应用上

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();
}

}

错误消息表示服务器试图将JSON对象解组为字符串,但预期会有所不同。

原因在于您的方法定义:

server.OnEvent("/", "msg", func(s socketio.Conn, msg string) string {

msg的类型为字符串。

然而,然后你会发送一条不同类型的消息:

public subscribe() {
this.socket.emit("msg", { msg: "Hello!" });
}

这个消息可以在这个结构定义中描述:

type Message struct {
Msg string `json:"msg"`
}

因此,将信息分解为字符串是不起作用的,因为您发送的对象不是字符串,而是必须以不同的方式表示。

要解决此问题,您有两个选项:

  1. 更改服务器端方法定义以能够接受客户端的数据:

    使用server.OnEvent("/", "msg", func(s socketio.Conn, msg Message) string {,注意msg现在的类型是Message,它是与接收到的数据匹配的结构。

  1. 更改客户端发送的数据:

    使用this.socket.emit("msg", "Hello!");只发送一个字符串(然后该字符串将被正确解码为字符串类型的msg参数。

最新更新