wsc.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //serverUrl
  2. var socketUrl = 'ws://127.0.0.1:9999';
  3. //保存websocket对象
  4. let socket;
  5. // reConnect函数节流标识符
  6. let flag = true;
  7. //心跳机制
  8. let heart = {
  9. timeOut:3000,
  10. timeObj : null,
  11. serverTimeObj : null,
  12. start:function(){
  13. console.log('start');
  14. let self = this;
  15. //清除延时器
  16. this.timeObj && clearTimeout(this.timeObj);
  17. this.serverTimeObj && clearTimeout(this.serverTimeObj);
  18. this.timeObj = setTimeout(function(){
  19. socket.send('兄弟,你还好吗?');//发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数
  20. //定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
  21. self.serverTimeObj=setTimeout(function(){
  22. socket.close();
  23. reConnect(socketUrl);
  24. },self.timeOut)
  25. },this.timeOut)
  26. }
  27. }
  28. //建立websocket连接函数
  29. function createWebsocket(url) {
  30. try {
  31. socket = new WebSocket(url);
  32. init();
  33. } catch (e) {
  34. //进行重连;
  35. console.log('websocket连接错误');
  36. reConnect(socketUrl);
  37. }
  38. }
  39. //对WebSocket各种事件进行监听
  40. function init() {
  41. socket.onopen = function () {
  42. //连接已经打开
  43. //重置心跳机制
  44. heart.start();
  45. }
  46. socket.onmessage = function (event) {
  47. //通过event.data获取server发送的信息
  48. //对数据进行操作
  49. console.log(event.data);
  50. //收到消息表示连接正常,所以重置心跳机制
  51. heart.start();
  52. }
  53. socket.onerror = function () {
  54. //报错+重连
  55. console.log('socket连接出错');
  56. reConnect(socketUrl);
  57. }
  58. socket.onclose = function () {
  59. console.log('socket连接关闭');
  60. }
  61. }
  62. //重连函数
  63. //因为重连函数会被socket事件频繁触发,所以通过函数节流限制重连请求发送
  64. function reConnect(url) {
  65. if (!flag) {
  66. return;
  67. }
  68. flag = false;
  69. setTimeout(function () {
  70. createWebsocket(url);
  71. flag = true;
  72. }, 3000)
  73. }