123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- import config from '../config'
- import storage from './storage'
- import {navigateTo} from './utils'
- export default {
-
- connected: false,
- connecting: false,
- socketTask: false,
- timer: 3000,
- link:0,
-
- /**
- * 创建 WebSocket 连接。
- */
- connect(kf_id){
- let users = storage.getJson("users");
- if(users == null){
- navigateTo("public/login");
- return false;
- }
-
- if(this.isConnect()){
- return false;
- }
-
- this.connecting = true;
- this.socketTask = uni.connectSocket({
- url: config.web_socket_url,
- header: {
- 'content-type': 'application/json'
- },
- complete: ()=> {}
- });
-
- // 监听WebSocket连接打开事件。
- this.socketTask.onOpen((res) => {
- this.connecting = false
- this.connected = true
- this.send({type:"login", auth:users.token,service_id:kf_id});
- });
-
- this.error();
-
- this.close();
- },
-
- /**
- * 检查是否己连接
- */
- isConnect(){
- if (this.connected || this.connecting) {
- return true;
- }
-
- return false;
- },
-
- /**
- * 重新连接websocket
- */
- reConnect(){
- this.close();
- this.connect();
- },
-
- /**
- * 监听 WebSocket 接受到服务器的消息事件
- * @param {Object} callback
- */
- message(callback){
- if(this.socketTask != null && this.socketTask.onMessage){
- this.socketTask.onMessage(callback);
- }
- },
-
- send(data){
- if(typeof data == "object"){
- data = JSON.stringify(data);
- }
-
- let that = this;
- return new Promise((resolve, reject)=>{
- that.socketTask.send({
- data:data,
- success(res){
- resolve(res);
- },
- fail(err){
- reject(err);
- }
- })
- });
- },
-
- error(){
- this.socketTask.onError((err) => {
- this.connecting = false
- this.connected = false
- // uni.hideLoading()
- // uni.showModal({
- // content: '与服务器断开连接,请稍后再试',
- // showCancel: false
- // });
- });
- },
-
- close(){
- if(this.link > 2) {
- return ;
- }
-
- if (this.socketTask && this.socketTask.close) {
-
- this.socketTask.onClose((res) => {
- this.connected = false;
- this.socketTask = false;
- this.link+=1;
- setTimeout(()=>{
- //this.connect();
- },this.timer);
- })
- }
- }
- }
|