websocket.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import Stomp from "stompjs";
  2. import store from '@store/index';
  3. var projectconfig = `ws://${window.__MODE__.websocketUrl}`;
  4. // ============================一般使用的变量============================
  5. let number = 0;
  6. export const datainit = initialize;
  7. export const webtest = test;
  8. // ============================ 大函数体 ============================
  9. function initialize (topic, adpClient) {
  10. if (adpClient != null) {
  11. adpClient.disconnect();
  12. }
  13. var url = projectconfig;
  14. // let socket = new SockJS(url); // 这个地址要找你们后端
  15. // adpClient = Stomp.over(socket);
  16. adpClient = Stomp.client(url);
  17. adpClient.debug = null;
  18. adpClient.connect({ topic: topic, authToken: localStorage.getItem('authToken') }, adpClient2 => connectCallBackSubscribe(adpClient, topic), error => reconnect(error, adpClient, topic));
  19. return adpClient;
  20. }
  21. // 断线重连
  22. function reconnect (error, adpClient, topic) {
  23. //连接失败时再次调用函数
  24. number++;
  25. adpClient.connected = false;
  26. clearTimeout(setTimeout(initialize(topic), 1000 * 60 * 5));
  27. debugX("DataAdapter reconnect:" + number + " 次");
  28. return;
  29. }
  30. // ============================ 订阅函数体 ============================
  31. function connectCallBackSubscribe (adpClient, topic) {
  32. number = 0;
  33. adpClient.connected = true;
  34. adpClient.subscribe(topic, stompMessage => reflexWindturbineBasicInformation(stompMessage));
  35. }
  36. // ============================ 解析函数体 ============================
  37. function reflexWindturbineBasicInformation (stompMessage) {
  38. var newdata = JSON.parse(stompMessage.body);
  39. store.dispatch('getupdate', newdata);
  40. // console.log("newdata", newdata)
  41. }
  42. // ============================ 其他 ============================
  43. function debugX (text) {
  44. console.log("text", text);
  45. }
  46. function test () {
  47. clearTimeout(setTimeout(initialize('/topic/detial/param_MG01_02'), 1000 * 60 * 2));
  48. }