为什么拍照测评要使用ws协议来做;
因为要实时 返回数据 , 评测过程中数据能动态展示; 比如进度条功能 、教培评测的单字评测实时渲染
拍照测评的流程
1,获取相机和本地相册权限
uni. getSetting ( { success : ( res ) => { if ( ! res. authSetting[ "scope.camera" ] ) { uni. authorize ( { scope : 'scope.camera' , success ( res ) { that. showCamera = true ; } , fail ( ) { uni. showModal ( { content : '检测到您没打开获取相机功能权限,是否去设置打开?' , confirmText : "确认" , cancelText : '取消' , success : ( res ) => { } , fail ( ) { } } ) } } ) } }
} )
2,页面初始化的时候,初始化websocket;
initWebSocket ( ) { let url = this . $apiHub. ws + 'xxxxxxxx' uni. connectSocket ( { url : url, header : { Origin : 'xxxxxxxxxxxxxxx.com' } , success ( ) { console. log ( 'webSocket链接成功' ) } , fail : err => { console. log ( 'webSocket链接失败' ) } } ) uni. onSocketOpen ( res => { this . reconnectCount = 5 ; this . heartbeat = setInterval ( ( ) => { this . sendMsg ( 'ping' ) } , 5000 ) } ) ; uni. onSocketError ( res => { clearInterval ( this . heartbeat) if ( ! this . socketClose) { this . reconnect ( url) } } ) ; uni. onSocketClose ( e => { clearInterval ( this . heartbeat) if ( ! this . socketClose) { this . reconnect ( url) } } ) ; uni. onSocketMessage ( res => { if ( res. data && res. data !== 'pong' ) { let resd = JSON . parse ( res. data) ; if ( resd. msg. progressRate) { this . precent = resd. msg. progressRate; } } } )
}
3,发送消息到websocket
sendMsg ( msg ) { if ( msg != 'ping' ) { } try { uni. sendSocketMessage ( { data : msg} ) } catch ( e) { uni. closeSocket ( ) }
} ,
4,上传完图片的时候调用 sendMsg() 发送消息
let cos = new COS ( { SecretId : 'xxxx' , SecretKey : 'xxxxx'
} )
const that = this ;
cos. postObject ( { Bucket : 'ccccc' , Region : 'ap-ssss' , Key : 'ssss/aaaaaa/' + Date. parse ( new Date ( ) ) + '/' + '.png' , FilePath : this . image} , function ( err, data ) { this . sendMsg ( JSON . stringify ( data) ) }
} ) ;