网页使用websocket

 

 

function MySocket(path){
    this.path=path
    var that=this
    this.timer=null
    this.tout=null
    this.init=function() {
        

        if (typeof(WebSocket) === "undefined") {
            alert("您的浏览器不支持socket")
        } else {
            // 实例化socket
            this.socket = new WebSocket(this.path)
            // 监听socket连接
            this.socket.onopen = this.open
            // 监听socket错误信息
            this.socket.onerror = this.error
            // 监听socket消息
            this.socket.onmessage = this.getMessage
            this.socket.onclose = this.close
            let this_socket=this.socket
            try{
                clearInterval(that.timer)
            }catch(e){
                //TODO handle the exception
            }
            
            that.timer=setInterval(function(){
                this_socket.send(1)
            },10000)
        }
        // console.log(this.socket)
    }


    this.open=function() {
        console.log("socket连接成功")



    }
    this.error=function() {
        try{
            clearInterval(that.timer)

            clearTimeout(that.tout)
        }catch(e){
            //TODO handle the exception
        }
        console.log("连接错误,正在重连")
        that.tout=setTimeout(function(){
            that.init()
        },3000)
        // this.init()


        // this.socket = new WebSocket(this.path)
    }
    this.getMessage=function(msg) {
        console.log(msg)
    }
    this.send=function(params) {
        
    }
    this.close=function(evt) {
        // 重连
        try{
            clearInterval(that.timer)

            clearTimeout(that.tout)
        }catch(e){
            //TODO handle the exception
        }
        console.log("连接错误,正在重连")
        that.tout=setTimeout(function(){
            that.init()
        },3000)
        // console.log(evt.code)
        // console.log(this.socket)
    }
}
 

 

使用:

var socket1=new MySocket('path')
socket1.init()

 

posted @ 2021-04-02 15:23  A-zero  阅读(436)  评论(0编辑  收藏  举报