# mt.connectSocket(Object object)
创建一个 WebSocket 连接。
# 支持情况
| 项 | 说明 |
|---|---|
| 兼容性 | 部分兼容 |
# 参数
Object object
| 属性 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| url | string | — | 是 | WebSocket 服务器地址(必须以 wss:// 或 ws:// 开头) |
| header | Object | — | 否 | HTTP Header |
| protocols | Array.<string> | — | 否 | 子协议数组 |
| perMessageDeflate | boolean | — | 否 | 是否开启消息压缩 |
| timeout | number | — | 否 | 连接超时时间,单位 ms |
| success | function | — | 否 | 成功回调 |
| fail | function | — | 否 | 失败回调 |
| complete | function | — | 否 | 完成回调(成功或失败均触发) |
# 返回值
返回 SocketTask 对象。
# 示例代码
const task = mt.connectSocket({
url: 'wss://example.com/socket',
protocols: ['protocol1'],
success() {
console.log('连接建立中')
}
})
task.onOpen(() => {
console.log('WebSocket 已连接')
task.send({ data: 'hello' })
})
task.onMessage((e) => {
console.log('收到消息:', e.data)
})
task.onClose((e) => {
console.log('连接已关闭')
})
# 与微信差异
origin固定为http://127.0.0.1,无法通过参数自定义(微信支持通过header.origin设置)。- 不支持微信的
tcpNoDelay(TCP 无延迟)、forceCellularNetwork(强制蜂窝网络)、type(连接类型)参数。