后端代码:
func WsHandler(c *gin.Context) {
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
client := wsserver.Client{
Id: wsserver.AutoId(),
Connection: conn,
IsConnect: true,
MessageCh: make(chan wsserver.WsMessage),
}
global.GD_WS.AddClient(client)
// defer conn.Close()
fmt.Println("New Client is connected, total: ", len(global.GD_WS.Clients))
go handleReciveMsg(client)
go global.GD_WS.PublishNew(client)
}
//路由器:
func initWebsocketRouter(Router *gin.RouterGroup) {
Router.GET("ws",apis.WsHandler)
}
最终的路由器路径是: “/系统/ws”
//首页代码:
const wsInit =async()=>{
const ws = window.WebSocket ? new WebSocket('ws://127.0.0.1:6666/system/ws') : null
ws.onopen = function () {
console.log('success!')
ws.send('startting...')
}
ws.onclose = function () {
console.log('close')
}
ws.onerror = function () {
console.log('error')
}
ws.onmessage = function (e) {
console.log(e.data)
}
//
}
wsInit()
然后我得到了错误: “与‘ws://127.0.0.1:6666/system/ws’的 WebSocket 连接失败:”无缘无故
但是在单个nodejs文件中它工作正常,nodejs文件代码崩溃了:
var WebSocketClient = require('websocket').client;
var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
connection.send('{"action":"subscribe","topic":"coin"}')
connection.send('{"action":"subscribe","topic":"gas"}')
});
client.connect('ws://localhost:6666/system/ws');
为什么会出现这种情况?
希望有人能帮忙,这已经让我困惑了两天
你能告诉我,你是如何解决这个问题的吗...我也陷入其中。