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()
  • 相关阅读:
    B题 hdu 1407 测试你是否和LTC水平一样高
    A题 hdu 1235 统计同成绩学生人数
    hdu 1869 六度分离(最短路floyd)
    hdu 2795 Billboard(线段树+单点更新)
    hdu 1754 I Hate It(线段树)
    hdu 1166敌兵布阵(线段树)
    hdu 1556(线段树之扫描线)
    Contest2073
    中南oj String and Arrays
    51nod 1459 迷宫游戏 (最短路径—Dijkstra算法)
  • 原文地址:https://www.cnblogs.com/azure-zero/p/14610867.html
Copyright © 2011-2022 走看看