• 网页使用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()
  • 相关阅读:
    迷宫与宝藏
    黑暗城堡
    Escaping the Farm
    Word Search
    描述
    防范sql注入值得注意地方
    fineui 实现下拉框模糊查询
    Fineui 根据datatable结构动态创建grid列,帮助类。动态绑定grid。
    Fineui 实现点击左边树状主菜单链接 打开新窗口或打开多个同一个tab
    fineui grid自定义选项框 带全选
  • 原文地址:https://www.cnblogs.com/azure-zero/p/14610867.html
Copyright © 2020-2023  润新知