webSocket.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. $(function(){
  2. openSocket(socketUrl);
  3. });
  4. let socket;
  5. let socketUrl="ws://localhost:8080/qk/webSocket/"+$("#loginName").val();
  6. function openSocket(url) {
  7. if(typeof(WebSocket) == "undefined") {
  8. console.log("您的浏览器不支持WebSocket");
  9. }else{
  10. console.log("您的浏览器支持WebSocket");
  11. //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  12. if(socket!=null){
  13. socket.close();
  14. socket=null;
  15. }
  16. socket = new WebSocket(url);
  17. //打开事件
  18. socket.onopen = function() {
  19. heartCheck.start();
  20. console.log("websocket已打开");
  21. };
  22. //获得消息事件
  23. socket.onmessage = function(msg) {
  24. heartCheck.reset();
  25. if(msg.data != "HeartBeat"){//如果不是心跳信息,执行业务
  26. //发现消息进入 开始处理前端触发逻辑
  27. let opt = JSON.parse(msg.data);
  28. //落点并飞行至该点
  29. $.eventPoint.addMarkAndFlyTo(opt);
  30. //刷新统计图数据
  31. let deptId = $(".onthis").attr("deptId") == null ? 0 : $(".onthis").attr("deptId");
  32. let year = $("#year").val();
  33. $.initData.getEvents(deptId,year);
  34. }
  35. console.log(msg.data);
  36. };
  37. //关闭事件
  38. socket.onclose = function() {
  39. console.log("websocket已关闭");
  40. reconnect(url);
  41. };
  42. //发生了错误事件
  43. socket.onerror = function() {
  44. console.log("websocket发生了错误");
  45. reconnect(url);
  46. }
  47. }
  48. }
  49. let lockReconnect = false;//避免重复连接
  50. function reconnect(url) {
  51. if (lockReconnect) return;
  52. lockReconnect = true;
  53. //没连接上会一直重连,设置延迟避免请求过多
  54. setTimeout(function () {
  55. openSocket(socketUrl);
  56. console.log("正在重连,当前时间" + new Date())
  57. lockReconnect = false;
  58. }, 5000); //这里设置重连间隔(ms)
  59. }
  60. let heartCheck = {
  61. timeout: 5000,//5s
  62. timeoutObj: null,
  63. reset: function(){
  64. clearInterval(this.timeoutObj);
  65. this.start();
  66. },
  67. start: function(){
  68. this.timeoutObj = setInterval(function(){
  69. if(socket.readyState==1){
  70. socket.send("HeartBeat");
  71. }
  72. }, this.timeout)
  73. }
  74. };