一.封装
TypeScript
import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
//执行UDP通讯的对象
let udpSocket:socket.UDPSocket= socket.constructUDPSocketInstance();
// 连接成功变量
let bindSuccess = false
export class UDPUtils {
//ArrayBuffer转utf8字符串
buf2String(buf: ArrayBuffer) {
let msgArray = new Uint8Array(buf);
let textDecoder = util.TextDecoder.create("utf-8");
return textDecoder.decodeWithStream(msgArray)
}
startHeart(address:string,port:number){
setInterval(()=>{
if(bindSuccess){
let remoteAddress:socket.NetAddress = { address: address, port: port, family: 1 }
udpSocket.send({ data: '心跳', address: remoteAddress })
.then(async () => {
console.log('心跳')
// this.msgHistory += "我:" +'心跳' + await getCurrentTimeString() + "\r\n"
})
.catch((e:BusinessError) => {
console.log('发送失败')
// this.msgHistory += '发送失败' + e.message + "\r\n";
})
}
},3000)
}
/**
* 绑定地址端口
* @param address:服务器ip
* @returns prot:端口号
*/
async bind2Port(address:string,prot:number) {
// await udpSocket.close()
// .then(() => {
// // this.bindSuccess= true
// console.log('注销成功');
// }).catch((err: BusinessError) => {
// console.log('注销失败');
// });
//本地地址
let localAddress:socket.NetAddress = { address: address, port: prot, family: 1 }
await udpSocket.bind(localAddress)
.then(() => {
bindSuccess = true
console.log('连接成功')
})
.catch((e:BusinessError) => {
console.log('连接失败')
})
//收到消息时的处理
udpSocket.on("message", async (value:socket.SocketMessageInfo)=> {
// 发送的消息
let msg = this.buf2String(value.message)
// ip
let remoteIP:string = value.remoteInfo.address
//端口
let remotePort:string = value.remoteInfo.port.toString()
//对端ip地址和端口的字符串形式
let remoteAddr:string = "[" + remoteIP + ":" + remotePort + "]:"
let msgHistory:string = remoteAddr + msg + "\r\n"
console.log('接收的消息:',msgHistory)
return msgHistory
})
}
/**
* 发送消息
* @param sendMsg:需要发送的消息
* @param address:服务器ip
* @param prot: 端口号
*/
sendMsg2Target(sendMsg:string,address:string,prot:number) {
//目的ip和端口
let remoteAddress:socket.NetAddress = { address: address, port: prot, family: 1 }
udpSocket.send({ data: sendMsg, address: remoteAddress })
.then(async () => {
console.log('发送的消息:',sendMsg)
})
.catch((e:BusinessError) => {
console.log('发送失败:',e.message)
})
}
}
二.使用
TypeScript
this.UDPUtils.bind2Port("0.0.0.0",9990)
// 心跳
this.UDPUtils.startHeart("0.0.0.0",9990)