123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- const _WEBSOCKET = {
- //是否打开连接
- isOpen: false,
- //连接socket
- connectSocket(url,successFunc = null, errorFunc = null) {
- try {
- //连接socket
- uni.connectSocket({
- url,
- success() {
- console.log('websocket连接成功!')
- }
- })
- //监听socket连接
- uni.onSocketOpen((res) => {
- this.isOpen = true
- console.log('WebSocket连接已打开!')
- if (successFunc) {
- successFunc(res)
- }
- })
- //监听socket连接失败
- uni.onSocketError((res) => {
- this.isOpen = false
- console.log('WebSocket连接打开失败,请检查!')
- if (errorFunc) {
- errorFunc(res)
- }
- })
- //监听收到消息
- uni.onSocketMessage((res) => {
- console.log('收到服务器内容:' + res.data)
- // const params = {
- // inApp: true, // app内横幅提醒
- // voice: true, // 声音提醒
- // vibration: true, // 振动提醒
- // messageType: '', //消息分类
- // messageTitle: '', //通知标题
- // messageContent: '中药煎配溯源管理来新处方啦!',
- // messageImage: ''
- // }
- // #ifdef APP-ANDROID
- const plugin = uni.requireNativePlugin("DCloud-PushSound");
- plugin.setCustomPushChannel({
- soundName: "tips",
- channelId: "消息通知",
- channelDesc:"中药煎配溯源管理来新处方啦",
- enableLights:true,
- enableVibration:true,
- importance:4,
- lockscreenVisibility:1
- });
- // #endif
- uni.redirectTo({
- url:"/pages/index/index"
- })
- })
- //监听socket关闭
- uni.onSocketClose((res) => {
- console.log('WebSocket 已关闭!')
- this.isOpen = false
- })
- } catch (error) {
- console.log('err:' + error)
- }
- },
- //发送消息
- sendMessage(msg = '', successFunc = null, errorFunc = null) {
- if (!this.isOpen || !msg) {
- if (errorFunc) {
- errorFunc('未传消息内容或连接未打开!')
- }
- return
- }
- uni.sendSocketMessage({
- data: msg,
- success(res) {
- console.log('消息发送成功!')
- if (successFunc) {
- successFunc(res)
- }
- },
- fail(err) {
- console.log('消息发送失败!')
- if (errorFunc) {
- errorFunc(err)
- }
- }
- })
- },
- //关闭连接
- closeSocket() {
- if (!this.isOpen) {
- return
- }
- //关闭socket连接
- uni.closeSocket()
- }
- }
- export default _WEBSOCKET
|