标签:open return send color == i++ 数据 json message
// 创建 websocket.js 文件夹 let wsurl = ‘ws://82.157.123.54:9010/ajaxchattest‘ let ws = null let weboscket_callback = null //获取 websocket 推送的数据 let websocketonmessage = e => { return weboscket_callback(e) } // 连接成功 let websocketonopen = () => { console.log(‘连接 websocket 成功‘) } // 连接失败时重新连接 let websocketonerror = () => { initWebSocket() } // 断开链接后报错 let websocketclose = e => { console.log(‘断开连接‘, e) } // 手动关闭 websocket let closewebsocket = () => { ws.close() } let initWebSocket = () => { //初始化 websocket ws = new WebSocket(wsurl) ws.onmessage = websocketonmessage ws.onopen = websocketonopen ws.onerror = websocketonerror ws.onclose = websocketclose } // 发送数据 let sendData = (data, callback) => { weboscket_callback = callback if (typeof data == ‘string‘) { data = data } else { data = JSON.stringify(data) } switch (ws.readyState) { case 0: setTimeout(() => { ws.send(data) }, 1000) break case 1: ws.send(data) break case 3: initWebSocket() setTimeout(() => { ws.send(data) }, 1000) break } } initWebSocket() export { sendData, closewebsocket }
在组件中引用:
标签:open return send color == i++ 数据 json message
原文地址:https://www.cnblogs.com/lyt520/p/14921989.html