12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import config from '../config'
- import storage from './storage'
- import {navigateTo} from './utils'
- export default {
- socketTask: null,
- timer: null,
- /**
- * 创建 WebSocket 连接。
- */
- connect(){
- let users = storage.getJson("users");
- let token = storage.getJson("token");
- let stationCode=storage.get("stationCode")
- if(users == null || token == null){
- navigateTo("public/login");
- return false;
- }
- if(this.timer !=null){
- clearInterval(this.timer)
- this.timer=null
- }
- if(this.socketTask!=null){
- this.socketTask.close();
- }
- this.socketTask = uni.connectSocket({
- url: config.web_socket_url+stationCode+'/'+token,
- header: {
- 'content-type': 'application/json'
- },
- complete: ()=> {}
- });
- // 监听WebSocket连接打开事件。
- this.socketTask.onOpen(() => {
- console.log('WebSocket连接已打开!');
- this.onSocketOpen()
- });
- //接收服务器数据事件
- this.socketTask.onMessage(res=>{
- this.onSocketMsg(res)
- })
- //监听WebSocket关闭事件
- this.socketTask.onClose(()=>{
- console.log('WebSocket连接已关闭!');
- })
- this.socketTask.onError(()=>{
- console.log("WebSocket连接错误")
- })
- if(this.timer ==null){
- this.timer=setInterval(()=>{
- if(this.socketTask.readyState!=1){
- this.socketTask.close()
- this.connect()
- }
- },2000)
- }
- },
- onSocketOpen(){},
- onSocketMsg(){},
- sendmessage(msg){
- this.socketTask.send({data:JSON.stringify(msg)})
- },
- }
|