websocket 封装

0

var websock = null;
var global_callback = null;
var serverPort = '8000'; //webSocket连接端口

// function getWebIP(){
// var curIP = window.location.hostname;
// return curIP;
// }

function initWebSocket(){ //初始化weosocket

//ws地址
// var wsuri = "ws://" +getWebIP()+ ":" + serverPort;
let wsuri = "ws://172.16.70.100:9999/qd/userLongConnect"; //无(上一步、下一步) designId
// let wsuri = "ws://172.16.70.100:9999/qd/longConn"
websock = new WebSocket(wsuri);
websock.onopen = function () {
    websocketOpen();
    websock.send({flag: 3, designId: "1234567890" });
}
websock.onmessage = function(e){
    websocketonmessage(e);
} 
websock.onclose = function(e){
    websocketclose(e);
}
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 websocketOpen(){

console.log("连接成功");

}

//数据接收
function websocketonmessage(msg){

return global_callback(msg.data);

}
//数据发送
function websocketsend(agentData){

let value = JSON.stringify(agentData);
websock.send(value);

}

//关闭
function websocketclose(){

console.log("连接关闭");

}

initWebSocket();

export {

sendSock,
websocketclose,

}

你可能感兴趣的

fish_uncle · 9月5日

重连机制都没有

回复

载入中...