websocket通讯 demo

前端代码

新建一个websocket.js

var websock = null;
var global_callback = null;
 
function initWebSocket(url){ //初始化weosocket
    // 处理地址转化ws
    if(url.indexOf('https')!=-1){
      url='ws'+url.substring(5)
    }else if(url.indexOf('http')!=-1){
      url='ws'+url.substring(4)
    }
    //ws地址
    websock = new WebSocket(url);
    websock.onmessage = function(e){
        websocketonmessage(e);
    } 
    websock.onclose = function(e){
        websocketclose(e);
    }
    console.log(url)
    websock.onopen = function () {
        websocketOpen();
    }
    
    //连接发生错误的回调方法
    websock.onerror = function () {
        console.log("WebSocket连接发生错误");
    }
}
 
// 实际调用的方法
function sendSock(agentData,callback){  
    global_callback = callback;
    if (websock.readyState === websock.OPEN) {
        //若是ws开启状态
        websocketsend(agentData)
    }else if (websock.readyState === websock.CONNECTING) {
        // 若是 正在开启状态,则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData,callback);
        }, 1000);
    }else {
        // 若未开启 ,则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData,callback);
        }, 1000);
    }
}
 
//数据接收
function websocketonmessage(e){ 
    global_callback(JSON.parse(e.data));
}
 
//数据发送
function websocketsend(agentData){
    websock.send(JSON.stringify(agentData));
}
 
//关闭
function websocketclose(e){  
    console.log("connection closed (" + e.code + ")");
}
 
function websocketOpen(e){
    console.log("连接成功");
}
 
 
export default{sendSock,initWebSocket}

组件中运用

import ws from '../../common/websocket'

// 实时通讯
      let url=this.$api.getJavaEndPoint()+'websocket/'+1
      ws.initWebSocket(url)
      ws.sendSock('nimei',res=>{
        console.log("发送成功")
      })

你可能感兴趣的:(h5)