示例代码:
import socket from '@ohos.net.socket';
import hilog from '@ohos.hilog';
import wifi from '@ohos.wifiManager';
import {resolveIP} from '../common/utils/Utils'
let localAddress = resolveIP(wifi.getIpInfo().ipAddress);
let localPort = 8081;
@Entry
@Component
struct TestUdpPage {
@State message: string = 'Hello World'
@State value:string = ''
@State address:string = '192.168.100.101' // 连接的IP地址
@State port:number = 8083 // 连接的端口号
@State sendValue:string = '' // 输入框中要发送的值
@State saveValue:string = 'Hi' // 存储UDPServer发送的信息
private UDPSocket:socket.UDPSocket = null;
async closeUDP():Promise<void>{
await this.UDPSocket.close();
this.UDPSocket.off('message');
this.UDPSocket = null;
}
async createUDP(){
this.UDPSocket = socket.constructUDPSocketInstance()
this.UDPSocket.bind({
address:localAddress,
port:localPort,
family:1
});
}
async sendData(data:string,address:string,port:number):Promise<void>
{
let option={
address:{
address:address,
port:port,
family:1
},
data:data
}
this.UDPSocket.send(option)
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Row(){
Text('发送信息')
TextInput({placeholder:'想要发送的内容'}).width('80%')
.onChange((value:string)=>{
this.sendValue = value;
})
}.width('80%')
Button('发送').width('50%').margin({top:10,bottom:50})
.onClick((event)=>{
if(this.sendValue!='')
{
this.sendData(this.sendValue,this.address,this.port)
}
})
Row(){
Text('接收信息')
Text(){
Span(this.saveValue).fontColor(Color.Green).fontSize(30)
}
}.width('80%')
}
.width('100%').height('100%')
}
.height('100%')
}
aboutToAppear()
{
this.createUDP()
this.UDPSocket.on('message',(data)=>{
hilog.info(0x0000,'TestTag',JSON.stringify(data))
let buffer = data.message
let dataview = new DataView(buffer)
let str= ""
for(let i = 0; i<dataview.byteLength; ++i)
{
str+= String.fromCharCode(dataview.getUint8(i))
}
this.saveValue = str
})
}
aboutToDisappear(){
this.closeUDP()
}
}
Utils.ets
export function resolveIP(ip: number): string {
if (ip < 0 || ip > 0xFFFFFFFF) {
throw new Error('The number is not normal!');
}
return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
}