websocket.js 704 B

12345678910111213141516171819202122232425262728
  1. import Vue from 'vue'
  2. let socket = null;
  3. const eventBus = new Vue(); // 使用一个小型事件总线通知页面
  4. export function connectWebSocket() {
  5. const url = '你的WebSocket地址'; // 替换为你的后端地址
  6. socket = uni.connectSocket({
  7. url: url,
  8. success: () => console.log('连接建立成功')
  9. });
  10. socket.onMessage(res => {
  11. const data = JSON.parse(res.data); // 假设返回的是 JSON 格式数据
  12. if (data.type === 'completed') {
  13. eventBus.$emit('websocket-message', data);
  14. }
  15. });
  16. socket.onError(err => {
  17. console.error('WebSocket错误:', err);
  18. });
  19. socket.onClose(() => {
  20. console.log('WebSocket已关闭');
  21. });
  22. }
  23. export { eventBus };