websocket 封装
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,
}
相关推荐
柳木木的IT 2020-11-04
joynet00 2020-09-23
wenf00 2020-09-14
蓝色深海 2020-08-16
wuychn 2020-08-16
取个好名字真难 2020-08-06
darylove 2020-06-26
shufen0 2020-06-20
Lovexinyang 2020-06-14
WangBowen 2020-06-14
firejq 2020-06-14
hjhmpl 2020-06-14
水痕 2020-06-07
guozewei0 2020-06-06
woniyu 2020-06-02
取个好名字真难 2020-06-01
guozewei0 2020-05-28
woniyu 2020-05-26