Ldc
2024-04-07 0652600959e5e3b5796fb6e8da129704ca95347a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * Created by dengbk on 2019/3/25.
 */
 
 
layui.define(['layer'],function(exports){
    var vciWebSocket = function(){
        this.url = {
            //$webUtil.getCurrentUserId()
            wsUrl:"ws://172.16.0.54:10000/vciMessageServer/mes208/"+$webUtil.getCurrentUserId()+"/"+$webUtil.getCurrentUserId()+""//websocket地址
        };
        this.websocket_connected_count = 0;
        this.onclose_connected_count = 0;
        this.config = {
            //wsUrl:"ws://localhost:10000/vciMessageServer/mes208/renky/renky",//服务器地址
            onopen:function(){
                //握手成功
            },
            onmessage:function(data){
                //收到消息
            }
        };
        this.serverTimeoutObj = "";//心跳
        this.linkSocket = "";
    };
    vciWebSocket.prototype.init = function(){
        var that = this;
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            that.linkSocket = new WebSocket(that.url.wsUrl);
            that.linkSocket.onopen = function() {
                console.log("Socket 已打开");
                that.config.onopen()
            };
            //获得消息事件
            that.linkSocket.onmessage = function(msg) {
                console.log(msg);
                that.heartCheck()
                that.config.onmessage(msg)
            };
            //关闭事件
            that.linkSocket.onclose = function(e) {
                console.log("Socket已关闭");
                console.log(e);
            };
            //发生了错误事件
            that.linkSocket.onerror = function() {
                that.websocket_connected_count++;
                if(that.websocket_connected_count <= 5){
 
                }
                console.log("Socket发生了错误");
            }
        }
    };
    vciWebSocket.prototype.heartCheck = function(){
        var that = this;
        that.heartCheckReset();
        that.heartCheckStart()
 
    };
    vciWebSocket.prototype.heartCheckReset = function(){
        var that = this;
        clearTimeout(that.serverTimeoutObj);
    };
    vciWebSocket.prototype.heartCheckStart = function(){
        var that = this;
        this.serverTimeoutObj = setInterval(function(){
            if(that.linkSocket.readyState == 1){
                console.log("连接状态,发送消息保持连接");
                that.linkSocket.send("ping");
               // that.heartCheck()    // 如果获取到消息,说明连接是正常的,重置心跳检测
            }else{
                console.log("断开状态,尝试重连");
            }
        }, 60000)
    };
    exports('vciWebSocket',new vciWebSocket())
});