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()
  • 相关阅读:
    GitHub之fetch:更新fork后的项目
    实验二 结对编程 第一阶段
    博客园之鼠标点击特效
    博客园之鼠标粒子吸附特效
    实验五 单元测试
    实验四 代码评审
    第三次实验 UML 建模工具的安装与使用
    结对编程(阶段二)
    结对编程第一阶段
    实验一 GIT 代码版本管理
  • 原文地址:https://www.cnblogs.com/azure-zero/p/14610867.html
Copyright © 2011-2022 走看看