新建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(e.data);
// global_callback(JSON.parse(e.data));
}
//数据发送
function websocketsend(agentData){
websock.send(agentData);
// websock.send(JSON.stringify(agentData));
}
//关闭
function websocketclose(e) {
websock.close()
console.log("connection closed (" + e + ")");
}
function websocketOpen(e){
console.log("连接成功");
}
export default{sendSock,initWebSocket,websocketclose}
我是局部使用
导入
import ws from "../../../../../utils/websocket";
使用
let url = "url;
ws.initWebSocket(url);
// 12345 为发送的参数 this.wsMessage 回调函数,用来处理返回值(methods中定义wsMessage(res)"{}方法)
ws.sendSock("12345", this.wsMessage);
// 关闭websocket
ws.websocketclose()
这样就表示连接成功