ws.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.msgCount={
  8. myMessageCount:'0',
  9. userId:'1111111'
  10. }
  11. ws.setInitSocket= function(uid){
  12. const user_id = userInfo.user_id;
  13. socket = new WebSocket(website.socket + user_id);
  14. socket.onopen = function (evt) {
  15. console.log('websocket链接成功');
  16. };
  17. socket.onclose = function (evt) {
  18. console.log('websocket连接已断开')
  19. };
  20. let that=this
  21. socket.onmessage = function ({data}) {
  22. if (data) {
  23. if(JSON.parse(data)!==null){
  24. ws.msgCount = JSON.parse(data)
  25. }
  26. }
  27. console.log(data,'消息信息')
  28. };
  29. socket.onerror = function ({data}) {
  30. console.log('发生错误:', data)
  31. };
  32. }
  33. ws.socketSend= function(uid){
  34. const user_id = userInfo.user_id;
  35. console.log('发送消息:',)
  36. if (socket) {
  37. socket.send(user_id);
  38. } else {
  39. setTimeout(()=>{
  40. socket.send(user_id);
  41. }, 1000)
  42. }
  43. }
  44. export default ws;