• 前端原生socket封装


    直接上代码

    1. var _this = '';
    2. function socket(url) {
    3. this.url = url;
    4. this.websocket = '';
    5. this.msg = '';
    6. this.lockReconnect = false;
    7. }
    8. // 初始化
    9. socket.prototype.initWebsocket = function() {
    10. if ('WebSocket' in window) {
    11. _this = this;
    12. this.websocket = new WebSocket(this.url);
    13. this.websocket.onerror = this.onError;
    14. this.websocket.onmessage = this.onMessage;
    15. this.websocket.onopen = this.onOpen;
    16. this.websocket.onclose = this.onClose;
    17. } else {
    18. console.log('错误:浏览器不支持websocket,请更换新版浏览器');
    19. }
    20. }
    21. // 连接异常处理
    22. socket.prototype.onError = function() {
    23. _this.msg = "websocket错误," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
    24. console.warn(_this.msg);
    25. // 重新连接
    26. _this.reconnect();
    27. }
    28. // 接收到消息处理
    29. socket.prototype.onMessage = function(event) {
    30. if (event.data == 'ok') {
    31. heartCheck.start();
    32. return;
    33. }
    34. window.dispatchEvent(new CustomEvent('onmessageWS', {
    35. detail: {
    36. data: event.data
    37. }
    38. }))
    39. // 通过下面接受消息 下面这个在其他js里
    40. // window.addEventListener("onmessageWS", function(e) {
    41. // console.log(e.detail)
    42. // })
    43. }
    44. // 关闭连接处理
    45. socket.prototype.onClose = function(e) {
    46. _this.msg = "websocket断开连接:" + new Date().toTimeString();
    47. console.log(_this.msg);
    48. console.log('日志:' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    49. if (e.code != 1000 && e.code != 1006) {
    50. // 重新连接
    51. _this.reconnect();
    52. }
    53. }
    54. // 打开连接处理
    55. socket.prototype.onOpen = function() {
    56. _this.msg = "websocket连接成功," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
    57. console.log(_this.msg);
    58. _this.websocket.send('加入websocket连接');
    59. // 心跳检测重置
    60. heartCheck.start();
    61. }
    62. // 主动关闭连接
    63. socket.prototype.close = function() {
    64. // 关闭socket连接
    65. _this.websocket.close();
    66. _this.lockReconnect = true;
    67. }
    68. // socket 重连
    69. socket.prototype.reconnect = function() {
    70. // 已经重连则取消后续操作
    71. if (_this.lockReconnect) return;
    72. _this.lockReconnect = true;
    73. // 没连接上会一直重连,设置延迟避免请求过多
    74. tt && clearTimeout(tt);
    75. _this.msg = '正在进行重连:' + new Date().toTimeString();
    76. console.log(_this.msg);
    77. var tt = setTimeout(function() {
    78. _this.initWebsocket();
    79. _this.lockReconnect = false;
    80. }, 5000);
    81. }
    82. let heartCheck = {
    83. timeout: 5000,
    84. timeoutObj: null,
    85. serverTimeoutObj: null,
    86. start: function() {
    87. let self = this;
    88. this.timeoutObj && clearTimeout(this.timeoutObj);
    89. this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    90. this.timeoutObj = setTimeout(function() {
    91. console.log('check socket heart beat……');
    92. //发送测试信息,后端收到后,返回一个消息,
    93. _this.websocket.send("ping");
    94. self.serverTimeoutObj = setTimeout(function() {
    95. _this.websocket.onerror();
    96. }, self.timeout)
    97. }, this.timeout);
    98. }
    99. }
    100. export { socket }

    调用

    1. sk = new socket(`ws://255,255,255,255:8080/socket/xxxx`);
    2. sk.initWebsocket();

  • 相关阅读:
    装配式建筑发展迎来发展新政,加快推进建筑业转型升级
    C#导出本机Win32native dll
    Wireshark新手小白基础使用方法
    VINS中的观测性问题
    如何写好CRUD?
    学习记录639@python机器学习模型部署与访问实战-基于Flask
    HTML5期末考核大作业,电影网站——橙色国外电影 web期末作业设计网页
    15、Java 多态的详细介绍(参考官方教程)
    【Linux】VM及WindowsServer安装
    lv5 嵌入式开发-11 消息队列
  • 原文地址:https://blog.csdn.net/weixin_43845059/article/details/132855386