更新记录
1.0.0(2025-05-03)
适用于Android的socket客户端插件
平台兼容性
Vue2 | Vue3 |
---|---|
√ | √ |
App | 快应用 | 微信小程序 | 支付宝小程序 | 百度小程序 | 字节小程序 | QQ小程序 |
---|---|---|---|---|---|---|
HBuilderX 3.6.8,Android:5.0,iOS:不支持,HarmonyNext:不支持 | × | × | × | × | × | × |
钉钉小程序 | 快手小程序 | 飞书小程序 | 京东小程序 | 鸿蒙元服务 |
---|---|---|---|---|
× | × | × | × | × |
H5-Safari | Android Browser | 微信浏览器(Android) | QQ浏览器(Android) | Chrome | IE | Edge | Firefox | PC-Safari |
---|---|---|---|---|---|---|---|---|
× | × | × | × | × | × | × | × | × |
lyy-socket
使用说明
createClient(options: ServerOptions, callback: Callback): ISocketClient
options: ServerOptions { ip: string, // 服务器ip port: number, // 服务器端口 heartInterval?: number | null, // 心跳间隔,默认30秒 heartMsg?: String | null // 心跳消息,默认 "HEARTBEAT" } callback: 回调接口 { onOpen: (clientId) => {}, // 客户端连接时调用 onMessage: (msg) => {}, // 接收到消息时调用,msg: 字节数组的base64字符串 onClose: (clientId) => {}, // 客户端关闭时调用 onError: (clientId, error) => {}, // 客户端异常时调用 } 返回值:client对象
client.sendMessage(message: string)
向服务端发送消息 message: 发送的消息,字节数组的base64字符串
client.close()
关闭客户端
示例
<script>
import { createClient, ISocketClient, Callback } from "../../uni_modules/lyy-socket"
export default {
data() {
return {
ip: "192.168.0.103",
port: 9999,
show: false,
clientMsg: null,
sendMsg: null,
receiveMsg: "",
client: null
}
},
methods: {
stop(){
this.client.close()
},
connect(){
const serverOptions = {
ip: this.ip,
port: this.port
}
const callback = {
onOpen: () => {
console.log('Client connected:', this.client);
this.show = true
},
onMessage: (message) => {
console.log('Client onMessage:', message);
try {
const decodedStr = this.base64ToUtf8(message);
this.receiveMsg += decodedStr;
} catch (e) {
console.error('Base64解码失败:', e);
}
},
onClose: () => {
console.log('Client disconnected:')
this.show = false
},
onError: (error) => {
console.error('Error:', error);
uni.showToast({ title: `客户端错误: ${error}`, icon: 'none' });
}
}
this.client = createClient(serverOptions, callback)
},
send(){
console.log('发送的数据', this.sendMsg)
if (!this.sendMsg) {
uni.showToast({ title: '消息内容不能为空', icon: 'none' });
return;
}
// 确保编码方法返回有效Uint8Array
const byteArray = this.encode(this.sendMsg);
if (byteArray.length === 0) {
return;
}
console.log("发送的消息长度:", byteArray.length);
this.client.sendMessage(this.uint8ArrayToBase64(byteArray))
},
encode(str) {
str = str || ""
if (typeof TextEncoder !== 'undefined') {
return new TextEncoder().encode(str);
}
// 兼容低版本浏览器
const bytes = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
},
uint8ArrayToBase64(bytes) {
let binary = '';
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
},
base64ToUtf8(base64) {
return decodeURIComponent(escape(atob(base64)));
}
}
}
</script>