ws.js 995 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import website from "@/config/website";
  2. import {getStore} from "@/util/store";
  3. import {getUserInfo} from '@/api/user'
  4. const userInfo = getStore({name: 'userInfo'}) || [];
  5. let ws = {};
  6. let socket
  7. ws.setInitSocket = function (uid) {
  8. const user_id = userInfo.user_id;
  9. socket = new WebSocket(website.socket + user_id);
  10. socket.onopen = function (evt) {
  11. console.log('link success');
  12. };
  13. socket.onclose = function (evt) {
  14. console.log('link break')
  15. };
  16. let that = this
  17. socket.onmessage = function ({data}) {
  18. if (data) {
  19. if (JSON.parse(data) !== null) {
  20. ws.msgCount = JSON.parse(data)
  21. }
  22. }
  23. //console.log(data, '消息信息')
  24. };
  25. socket.onerror = function ({data}) {
  26. console.log('link error:', data)
  27. };
  28. }
  29. ws.socketSend = function () {
  30. const data = "1,1,manager";
  31. //console.log('发送消息:', data)
  32. if (socket) {
  33. socket.send(data);
  34. } else {
  35. setTimeout(() => {
  36. socket.send(data);
  37. }, 1000)
  38. }
  39. }
  40. export default ws;