websocket-socketTask.uvue 5.8 KB
Newer Older
1
<template>
DCloud-WZF's avatar
DCloud-WZF 已提交
2 3 4 5
  <view>
    <page-head title="websocket通讯示例"></page-head>
    <view class="uni-padding-wrap">
      <view class="uni-btn-v">
Y
yurj26 已提交
6
        <text class="websocket-msg">{{ showMsg }}</text>
DCloud-WZF's avatar
DCloud-WZF 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20
        <button class="uni-btn-v" type="primary" @click="connect">
          连接websocket服务
        </button>
        <button
          class="uni-btn-v"
          v-show="connected"
          type="primary"
          @click="send"
        >
          发送一条消息
        </button>
        <button class="uni-btn-v" type="primary" @click="close">
          断开websocket服务
        </button>
Y
yurj26 已提交
21 22
        <text class="websocket-tips"
          >发送消息后会收到一条服务器返回的消息(与发送的消息内容一致)</text
DCloud-WZF's avatar
DCloud-WZF 已提交
23 24 25 26
        >
      </view>
    </view>
  </view>
27 28
</template>

Y
yurj26 已提交
29
<script lang="uts">
DCloud-WZF's avatar
DCloud-WZF 已提交
30 31 32 33 34 35 36 37
export default {
  data() {
    return {
      connected: false,
      connecting: false,
      socketTask: null as SocketTask | null,
      msg: '',
      platform: '',
38 39 40
      pageVisible: false,
      //自动化测试例专用
      jest_result: 0,
DCloud-WZF's avatar
DCloud-WZF 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }
  },
  computed: {
    showMsg(): string {
      if (this.connected) {
        if (this.msg.length > 0) {
          return '收到消息:' + this.msg
        } else {
          return '等待接收消息'
        }
      } else {
        return '尚未连接'
      }
    },
  },
  onLoad() {
    this.platform = uni.getSystemInfoSync().platform
    this.pageVisible = true
  },
  onUnload() {
    this.pageVisible = false
    uni.hideLoading()
    let task = this.socketTask
    if (task != null) {
      task.close({
        code: 1000,
        reason: 'close reason from client',
        success(res: any) {
          console.log('uni.closeSocket success', res)
        },
        fail(err: any) {
          console.log('uni.closeSocket fail', err)
        },
      } as CloseSocketOptions)
    }
  },
  methods: {
    connect() {
      if (this.connected || this.connecting) {
        uni.showModal({
          content: '正在连接或者已经连接,请勿重复连接',
          showCancel: false,
        })
        return
      }
      this.connecting = true
      uni.showLoading({
        title: '连接中...',
      })
      this.socketTask = uni.connectSocket({
        url: 'ws://websocket.dcloud.net.cn',
        success(res: any) {
          // 这里是接口调用成功的回调,不是连接成功的回调,请注意
          console.log('uni.connectSocket success', res)
        },
        fail(err: any) {
          // 这里是接口调用失败的回调,不是连接失败的回调,请注意
          console.log('uni.connectSocket fail', err)
        },
      })
      this.socketTask?.onOpen((res: any) => {
        if (this.pageVisible) {
          this.connecting = false
          this.connected = true
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '连接成功',
          })
          console.log('onOpen', res)
        }
      })
      this.socketTask?.onError((err: any) => {
        if (this.pageVisible) {
          this.connecting = false
          this.connected = false
          uni.hideLoading()
          uni.showModal({
            content: '连接失败,可能是websocket服务不可用,请稍后再试',
            showCancel: false,
          })
          console.log('onError', err)
        }
      })
      this.socketTask?.onMessage((res: OnSocketMessageCallbackResult) => {
        if (this.pageVisible) {
          this.msg = res.data as string
          console.log('onMessage', res)
        }
      })
      this.socketTask?.onClose((res: any) => {
        if (this.pageVisible) {
          this.connected = false
          this.socketTask = null
          this.msg = ''
          console.log('onClose', res)
        }
      })
    },
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
140
    send() {
DCloud-WZF's avatar
DCloud-WZF 已提交
141 142
      const data =
        'from ' +
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
143
        this.platform +
DCloud-WZF's avatar
DCloud-WZF 已提交
144 145 146 147 148
        ' : ' +
        parseInt(Math.random() * 10000 + '').toString()
      this.socketTask?.send({
        data,
        success(res: any) {
149
          console.log(res)
DCloud-WZF's avatar
DCloud-WZF 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        },
        fail(err: any) {
          console.log(err)
        },
      } as SendSocketMessageOptions)
    },
    close() {
      this.socketTask?.close({
        code: 1000,
        reason: 'close reason from client',
        success(res: any) {
          console.log('uni.closeSocket success', res)
        },
        fail(err: any) {
          console.log('uni.closeSocket fail', err)
        },
      } as CloseSocketOptions)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    },
    //自动化测试例专用
    jest_connectSocket(){
      this.socketTask = uni.connectSocket({
        url: 'ws://websocket.dcloud.net.cn',
        success:(_) => {
          this.jest_result++
        },
        fail:(_) => {
          this.jest_result = 0
        },
      })
      this.socketTask?.onOpen((_) => {
          const data =
            'from ' +
            this.platform +
            ' : ' +
            parseInt(Math.random() * 10000 + '').toString()
          this.socketTask?.send({
            data,
            success(_) {
              this.jest_result++
            },
            fail(_) {
              this.jest_result = 0
            },
          } as SendSocketMessageOptions)
      })
      this.socketTask?.onError((_) => {
          this.jest_result = 0;
      })
    }
DCloud-WZF's avatar
DCloud-WZF 已提交
199 200
  },
}
201 202 203
</script>

<style>
DCloud-WZF's avatar
DCloud-WZF 已提交
204 205 206
.uni-btn-v {
  padding: 10rpx 0;
}
207

DCloud-WZF's avatar
DCloud-WZF 已提交
208 209 210
.uni-btn-v {
  margin: 20rpx 0;
}
211

DCloud-WZF's avatar
DCloud-WZF 已提交
212 213 214 215 216 217 218
.websocket-msg {
  padding: 40px 0px;
  text-align: center;
  font-size: 14px;
  line-height: 40px;
  color: #666666;
}
219

DCloud-WZF's avatar
DCloud-WZF 已提交
220 221 222 223 224 225 226 227
.websocket-tips {
  padding: 40px 0px;
  text-align: center;
  font-size: 14px;
  line-height: 24px;
  color: #666666;
}
</style>