共计 1308 个字符,预计需要花费 4 分钟才能阅读完成。
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,
}
正文完
发表至: javascript
2019-09-05