zoukankan      html  css  js  c++  java
  • 网页使用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()
  • 相关阅读:
    关于接口是值类型还是引用类型的猜测
    絮语工作四年的碎碎念
    烧钱游戏加入创业公司的一些感想
    关于C#调用非托管动态库方式的性能疑问
    couchbase作为分布式session容器时的注意事项
    poj3624
    明天的下载链接
    poj 1502
    poj1459 多源多汇最大流
    poj 3041
  • 原文地址:https://www.cnblogs.com/azure-zero/p/14610867.html
Copyright © 2011-2022 走看看