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

我在 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


白衣非少年
浏览 236回答 1
1回答

哈士奇WWW

错误消息表明服务器尝试将您的 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"`}因此,将您的信息解组为字符串是行不通的,因为您发送的对象不是字符串,但必须以不同的方式表示。要解决此问题,您有两种选择:更改您的服务器端方法定义以能够接受客户端的数据:使用server.OnEvent("/", "msg", func(s socketio.Conn, msg Message) string {,注意msg现在是 type Message,这是与接收到的数据匹配的结构。或者更改客户端发送的数据:用于this.socket.emit("msg", "Hello!");仅发送一个字符串(然后将其正确解码为您msg的字符串类型参数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go