更新记录
1.0.0(2025-04-18)
适用于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-socketserver
适用于Android的socket服务端
使用说明
startSocketServer(port, heartTimeout, callback)
启动socket server port: 启动端口 heartTimeout: 心跳超时时间 callback: 回调接口 { onOpen: (clientId) => {}, // 客户端连接时调用 onMessage: (msg) => {}, // 接收到消息时调用,msg: 字节数组的base64字符串 onClose: (clientId) => {}, // 客户端关闭时调用 onError: (clientId, error) => {}, // 客户端异常时调用 } 返回值:server对象
server.sendMessage({clientId, msg})
向指定客户端发送消息 clientId: 客户端id msg: 发送的消息,字节数组的base64字符串
server.closeClient(clientId)
断开指定客户端 clientId: 客户端id
server.stopServer()
关闭socket server
示例
<script>
import { startSocketServer, sendMessage, stopServer } from '@/uni_modules/lyy-socketServer'
export default {
data() {
return {
port: 9999,
clientId: '',
message: '',
receive: '',
server: null
}
},
methods: {
stopServer(){
if(this.server){
this.server.stopServer();
this.show = false
}
},
openServer(){
console.log("启动服务器,端口:" + this.port)
const callback = {
onOpen: (client) => {
console.log('Client connected:', client);
this.clientId = client;
},
onMessage: (msg) => {
console.log('Client onMessage:', msg.client);
try {
const decodedStr = this.base64ToUtf8(msg.message);
this.receive += decodedStr;
} catch (e) {
console.error('Base64解码失败:', e);
}
},
onClose: (client) => {
console.log('Client disconnected:', client);
},
onError: (client, error) => { // 必须实现该方法
console.error('Error:', client, error);
uni.showToast({ title: `客户端${client}错误: ${error}`, icon: 'none' });
this.server.closeClient(client)
}
};
this.server = startSocketServer(this.port, 30000, callback)
if(this.server != null){
this.show = true;
}
},
send(){
console.log('发送的数据', this.message)
if (!this.message) {
uni.showToast({ title: '消息内容不能为空', icon: 'none' });
return;
}
// 确保编码方法返回有效Uint8Array
const byteArray = this.encode(this.message);
if (byteArray.length === 0) {
return;
}
console.log("发送的消息长度:", byteArray.length);
this.server.sendMessage({
client: this.clientId,
message: 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>