WebSocket接收不到发来的信息?

chat.js文件

export default class WebSocketService {
  constructor(url) {  
    this.socket = new WebSocket(url);  
    this.initSocket();  
  }  
  initSocket() {  
    this.socket.onopen = () => {  
      console.log('WebSocket Connected');  
    };  

    this.socket.onmessage = (event) => {  
      const data = JSON.parse(event.data); 
      this.handleMessage(data);  
    };  

    this.socket.onerror = (error) => {  
      console.error('WebSocket Error: ', error);  
    };  

    this.socket.onclose = () => {  
      console.log('WebSocket Disconnected');  
    };  
  }  

  sendMessage(message) {  
    if (this.socket.readyState === WebSocket.OPEN) {  
      this.socket.send(JSON.stringify(message));  
    } else {  
      console.error('WebSocket is not open. Unable to send message.');  
    }  
  }  

  handleMessage(data) {  

  }  
}

在main.js文件

import WebSocketService from '@/utils/chat';
import { baseURL } from '@/config'
const userId = 'PC_' + localStorage.getItem("userId")
  const _token = localStorage.getItem("admin-pro-token")
  let str = baseURL;
  let newStr
  if (process.env.NODE_ENV === 'development') {
    newStr = str.replace("http", "ws");
  } else {
    newStr = str.replace("https", "wss");
  }

const socketService = new WebSocketService(`${newStr}applet/user/chat/${userId}?token=Bearer%20` + _token);
Vue.prototype.$socket = socketService; 

在组件使用WebSocket

import { getUnreadNumberAll } from '@/api/chat'
methods: {
    async fetchData() {
      console.log(this.$socket.constructor);
      const data = await getUnreadNumberAll();
      this.badgeNumber = data.data
    },
}
created() {
  this.fetchData()
},

大佬们,在接收信息接收不到,这是什么原因呢,我的需求是在接收信息同时触发这个this.fetchData()方法,但是这样写接收不到

在接收信息接收不到,这是什么原因呢,我的需求是在接收信息同时触发这个this.fetchData()方法,但是这样写接收不到,怎么处理呢

阅读 2.7k
avatarAI BotBETA

WebSocket接收不到信息可能有多种原因。这里有几个可能的原因和对应的处理建议:

  1. URL不正确或服务器未运行

    • 确保你连接的WebSocket服务器地址是正确的,并且服务器正在运行且监听相应的端口。
    • 检查baseURL是否正确地替换成了wswss,并且路径和查询参数也正确无误。
  2. 网络问题

    • 确认网络连接正常,没有防火墙或其他网络限制阻止WebSocket连接。
  3. 认证问题

    • 如果WebSocket服务器需要认证,请确保在连接时提供了正确的认证信息(如token)。
    • 检查服务器是否对提供的token进行了验证,并且没有返回认证失败的响应。
  4. 服务器配置问题

    • 检查服务器端的WebSocket配置,确保它正确设置了响应消息的处理逻辑。
  5. 前端处理逻辑问题

    • handleMessage方法中,你并没有做任何处理。你需要在这个方法中实现接收消息后的处理逻辑。
    • 如果你想要在接收到消息时调用this.fetchData(),你需要在handleMessage方法中调用它。

针对你的代码,你可以尝试以下修改:

// chat.js文件
export default class WebSocketService {
  // ... 其他代码保持不变 ...

  handleMessage(data) {
    // 在这里处理接收到的消息
    console.log('Received data:', data);
    
    // 如果需要在接收到消息时调用fetchData,你可以在这里调用它
    // 但注意,fetchData是组件的方法,你需要确保正确传递和调用它
    // 如果你在WebSocketService类外部处理消息,那么你需要传递一个回调函数到WebSocketService
    // 或者使用Vue的事件系统来触发事件,并在组件中监听这个事件
  }
}

在组件中,你可以这样使用WebSocket服务:

// 组件内部
export default {
  // ... 其他代码保持不变 ...

  methods: {
    async fetchData() {
      console.log(this.$socket.constructor);
      const data = await getUnreadNumberAll();
      this.badgeNumber = data.data;
    },

    onMessageReceived(data) {
      // 这是一个假设的方法,用于处理从WebSocket接收到的消息
      console.log('Message received in component:', data);
      // 在这里可以调用fetchData或其他任何你需要的逻辑
      this.fetchData();
    },
  },

  created() {
    this.fetchData();

    // 假设WebSocketService类有一个方法允许你注册消息处理函数
    // this.$socket.onMessage(this.onMessageReceived);

    // 或者,你可以使用Vue的事件系统来触发和监听事件
    // 这样的话,你需要在WebSocketService类中触发一个自定义事件,并在组件中监听这个事件
  },

  beforeDestroy() {
    // 在组件销毁前关闭WebSocket连接
    if (this.$socket && this.$socket.socket) {
      this.$socket.socket.close();
    }
  },
};

注意:

  • this.$socket.onMessage(this.onMessageReceived); 是一个假设的方法,你需要根据你的WebSocketService类的实现来注册消息处理函数。
  • 在组件销毁前(beforeDestroy钩子),确保关闭WebSocket连接,以避免内存泄漏和其他潜在问题。

确保你检查了浏览器的控制台,看看是否有任何错误消息,这些消息可能会给出更多关于问题的线索。同时,使用浏览器的开发者工具的网络(Network)标签页来监视WebSocket连接和消息交换也是一个好习惯。

1 个回答

在这种情况下,接收不到WebSocket信息的原因可能有很多,下面是一些可能的原因及解决办法:

可能原因及解决办法
WebSocket连接没有正确建立:

请确保WebSocket URL正确无误,尤其是协议(ws或wss)和路径。
确认后端WebSocket服务器已正确启动并监听指定的路径。
消息格式或解析错误:

请确认后端发送的消息格式正确,并且前端解析消息时没有错误。
可以在this.socket.onmessage中添加更多的日志以调试:

this.socket.onmessage = (event) => {
  console.log('Message received: ', event.data);
  try {
    const data = JSON.parse(event.data);
    this.handleMessage(data);
  } catch (error) {
    console.error('Error parsing message: ', error);
  }
};

WebSocket服务实例在Vue组件中未正确注册或使用:

确保在组件中正确地使用this.$socket,并且在适当的生命周期钩子中进行处理。

handleMessage(data) {
  // 确保this指向组件实例
  Vue.prototype.$socket.componentInstance.fetchData();
}

检查连接状态:

可以在this.socket.onopen和this.socket.onclose中添加更多日志,确保连接状态正常:

this.socket.onopen = () => {
  console.log('WebSocket Connected');
};

this.socket.onclose = () => {
  console.log('WebSocket Disconnected');
};

代码调整示例
WebSocketService类
在handleMessage中触发组件的fetchData()方法。确保传入Vue实例以便在WebSocket中调用其方法。

export default class WebSocketService {
  constructor(url, componentInstance) {
    this.socket = new WebSocket(url);
    this.componentInstance = componentInstance;
    this.initSocket();
  }

  initSocket() {
    this.socket.onopen = () => {
      console.log('WebSocket Connected');
    };

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.handleMessage(data);
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket Error: ', error);
    };

    this.socket.onclose = () => {
      console.log('WebSocket Disconnected');
    };
  }

  sendMessage(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    } else {
      console.error('WebSocket is not open. Unable to send message.');
    }
  }

  handleMessage(data) {
    if (this.componentInstance) {
      this.componentInstance.fetchData();
    }
  }
}

在main.js中实例化WebSocketService并传入Vue实例

import WebSocketService from '@/utils/chat';
import { baseURL } from '@/config';
import Vue from 'vue';

const userId = 'PC_' + localStorage.getItem("userId");
const _token = localStorage.getItem("admin-pro-token");
let str = baseURL;
let newStr = process.env.NODE_ENV === 'development' ? str.replace("http", "ws") : str.replace("https", "wss");

Vue.prototype.$socket = new WebSocketService(`${newStr}applet/user/chat/${userId}?token=Bearer%20${_token}`, Vue);

在Vue组件中使用WebSocket
确保fetchData方法在WebSocketService的handleMessage中被调用:

import { getUnreadNumberAll } from '@/api/chat';

export default {
  methods: {
    async fetchData() {
      console.log('Fetching data...');
      const data = await getUnreadNumberAll();
      this.badgeNumber = data.data;
    },
  },
  created() {
    this.fetchData();
  },
};

调试步骤
确保WebSocket URL正确无误。
确认WebSocket连接已成功建立。
确认后端发送的消息格式正确,前端能够正确解析。
确保在Vue组件中正确注册并使用WebSocketService实例。
通过上述步骤,您应该能够解决WebSocket接收信息的问题,并在接收到信息时触发fetchData方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题