# uni.connectSocket(options)

创建一个 WebSocket 连接。

# # Parameters

name type required default description
options ConnectSocketOptions YES - -

# # ConnectSocketOptions Values

name type optinal default description
url string YES - 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
header UTSJSONObject NO null HTTP 请求 Header,header 中不能设置 Referer
protocols Array<string> NO null 子协议数组
success (result: ConnectSocketSuccess) => void NO null 接口调用成功的回调函数
fail (result: ConnectSocketFail) => void NO null 接口调用失败的回调函数
complete (result: any) => void NO null 接口调用结束的回调函数(调用成功、失败都会执行)
# # ConnectSocketSuccess Values
name type optinal default description
errMsg string YES - -
# # ConnectSocketFail Values
name type optinal default description
errCode number YES - 错误码 - 600009 URL格式不合法
errSubject string YES - 统一错误主题(模块)名称
data any NO - 错误信息中包含的数据
errMsg string YES - -

# # Return value

Type
SocketTask

# # SocketTask Values

name type optinal default description
send (options: SendSocketMessageOptions) => void YES - 通过 WebSocket 连接发送数据
close (options: CloseSocketOptions) => void YES - 关闭 WebSocket 连接
onOpen (callback: (result: OnSocketOpenCallbackResult) => void) => void YES - 监听 WebSocket 连接打开事件
onClose (callback: (result: any) => void) => void YES - 监听 WebSocket 连接关闭事件
onError (callback: (result: GeneralCallbackResult) => void) => void YES - 监听 WebSocket 错误
onMessage (callback: (result: OnSocketMessageCallbackResult) => void) => void YES - 监听 WebSocket 接受到服务器的消息事件
# # SendSocketMessageOptions Values
name type optinal default description
data any YES - 需要发送的内容
success (result: GeneralCallbackResult) => void NO null 接口调用成功的回调函数
fail (result: GeneralCallbackResult) => void NO null 接口调用失败的回调函数
complete (result: GeneralCallbackResult) => void NO null 接口调用结束的回调函数(调用成功、失败都会执行)
# # CloseSocketOptions Values
name type optinal default description
code number NO 1000 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
reason string NO "" 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
success (result: GeneralCallbackResult) => void NO null 接口调用成功的回调函数
fail (result: GeneralCallbackResult) => void NO null 接口调用失败的回调函数
complete (result: GeneralCallbackResult) => void NO null 接口调用结束的回调函数(调用成功、失败都会执行)
# # OnSocketOpenCallbackResult Values
name type optinal default description
header any YES - 连接成功的 HTTP 响应 Header
# # OnSocketMessageCallbackResult Values
name type optinal default description
data any YES - 服务器返回的消息
# # SocketTask Compatibility
Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
send 4.4 3.9+ 9.0 x
close 4.4 3.9+ 9.0 x
onOpen 4.4 3.9+ 9.0 x
onClose 4.4 3.9+ 9.0 x
onError 4.4 3.9+ 9.0 x
onMessage 4.4 3.9+ 9.0 x

# # connectSocket Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

connectSocket

Related Bug

# uni.onSocketOpen(options)

监听WebSocket连接打开事件。

# # Parameters

name type required default description
options (result: OnSocketOpenCallbackResult) => void YES - -

# # onSocketOpen Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

onSocketOpen

Related Bug

# uni.onSocketError(callback)

下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。

# # Parameters

name type required default description
callback (result: OnSocketErrorCallbackResult) => void YES - -

# # OnSocketErrorCallbackResult Values

name type optinal default description
errMsg string YES - 错误信息

# # onSocketError Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

onSocketError

Related Bug

# uni.sendSocketMessage(options)

通过 WebSocket 连接发送数据,需要先 uni.connectSocket,并在 uni.onSocketOpen 回调之后才能发送。

# # Parameters

name type required default description
options SendSocketMessageOptions YES - -

# # SendSocketMessageOptions Values

name type optinal default description
data any YES - 需要发送的内容
success (result: GeneralCallbackResult) => void NO null 接口调用成功的回调函数
fail (result: GeneralCallbackResult) => void NO null 接口调用失败的回调函数
complete (result: GeneralCallbackResult) => void NO null 接口调用结束的回调函数(调用成功、失败都会执行)

# # sendSocketMessage Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

sendSocketMessage

Related Bug

# 注意事项

  • 出于性能的权衡,在底层实现上发送队列占用的内存不能超过16M,一旦超过将导致连接被关闭。

# uni.onSocketMessage(callback)

监听WebSocket接受到服务器的消息事件。

# # Parameters

name type required default description
callback (result: OnSocketMessageCallbackResult) => void YES - -

# # OnSocketMessageCallbackResult Values

name type optinal default description
data any YES - 服务器返回的消息

# # onSocketMessage Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

onSocketMessage

Related Bug

# uni.closeSocket(options)

关闭 WebSocket 连接。

# # Parameters

name type required default description
options CloseSocketOptions YES - -

# # CloseSocketOptions Values

name type optinal default description
code number NO 1000 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
reason string NO "" 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
success (result: GeneralCallbackResult) => void NO null 接口调用成功的回调函数
fail (result: GeneralCallbackResult) => void NO null 接口调用失败的回调函数
complete (result: GeneralCallbackResult) => void NO null 接口调用结束的回调函数(调用成功、失败都会执行)

# # closeSocket Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

closeSocket

Related Bug

# uni.onSocketClose(callback)

监听WebSocket关闭。

# # Parameters

name type required default description
callback (result: OnSocketCloseCallbackResult) => void YES - -

# # OnSocketCloseCallbackResult Values

name type optinal default description
code number YES - 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。
reason string YES - 一个可读的字符串,表示连接被关闭的原因。

# # onSocketClose Compatibility

Android version Android uni-app Android uni-app-x iOS version iOS uni-app iOS uni-app-x
4.4 3.9+ 9.0 x

# # See also

onSocketClose

Related Bug

# # Example

hello uni-app x

<template>
 <view>
   <page-head title="websocket通讯示例"></page-head>
   <view class="uni-padding-wrap">
     <view class="uni-btn-v">
       <text class="websocket-msg">{{ showMsg }}</text>
       <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>
       <text class="websocket-tips">发送消息后会收到一条服务器返回的消息(与发送的消息内容一致)</text>
     </view>
   </view>
 </view>
</template>

<script lang="uts">
 export default {
   data() {
     return {
       connected: false,
       connecting: false,
       msg: '',
       roomId: '',
       platform: '',
     }
   },
   computed: {
     showMsg() : string {
       if (this.connected) {
         if (this.msg.length > 0) {
           return '收到消息:' + this.msg
         } else {
           return '等待接收消息'
         }
       } else {
         return '尚未连接'
       }
     },
   },
   onLoad() {
     this.platform = uni.getSystemInfoSync().platform
   },
   onUnload() {
     uni.closeSocket({
       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)
     uni.hideLoading()
   },
   methods: {
     connect() {
       if (this.connected || this.connecting) {
         uni.showModal({
           content: '正在连接或者已经连接,请勿重复连接',
           showCancel: false,
         })
         return
       }
       this.connecting = true
       uni.showLoading({
         title: '连接中...',
       })
       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)
         },
       })
       uni.onSocketOpen((res) => {
         this.connecting = false
         this.connected = true
         uni.hideLoading()

         uni.showToast({
           icon: 'none',
           title: '连接成功',
         })
         console.log('onOpen', res)
       })
       uni.onSocketError((err) => {
         this.connecting = false
         this.connected = false
         uni.hideLoading()

         uni.showModal({
           content: '连接失败,可能是websocket服务不可用,请稍后再试',
           showCancel: false,
         })
         console.log('onError', err)
       })
       uni.onSocketMessage((res) => {
         this.msg = res.data as string
         console.log('onMessage', res)
       })
       uni.onSocketClose((res) => {
         this.connected = false
         this.msg = ''
         console.log('onClose', res)
       })
     },
     send() {
       uni.sendSocketMessage({
         data:
           'from ' +
           this.platform +
           ' : ' +
           parseInt((Math.random() * 10000).toString()).toString(),
         success: (res : any) => {
           console.log(res)
         },
         fail: (err : any) => {
           console.log(err)
         },
       } as SendSocketMessageOptions)
     },
     close() {
       uni.closeSocket({
         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)
     },
   },
 }
</script>

<style>
 .uni-btn-v {
   padding: 10rpx 0;
 }

 .uni-btn-v {
   margin: 20rpx 0;
 }

 .websocket-room {
   height: 40px;
   line-height: 40px;
   text-align: center;
   border-bottom: solid 1px #dddddd;
   margin-bottom: 20px;
 }

 .websocket-msg {
   padding: 40px 0px;
   text-align: center;
   font-size: 14px;
   line-height: 40px;
   color: #666666;
 }

 .websocket-tips {
   padding: 40px 0px;
   text-align: center;
   font-size: 14px;
   line-height: 24px;
   color: #666666;
 }
</style>

# # General type

# # GeneralCallbackResult

name type optinal default description
errMsg string YES - 错误信息