api9开发,代码如下:
mport socket from '@ohos.net.socket';
import util from '@ohos.util';
const TAG: string = 'UdpPage';
@Entry
@Component
struct UdpPage {
udp: socket.UDPSocket = socket.constructUDPSocketInstance();
@State receiveMessage: string = ''; //收到数据
build() {
Row() {
Column() {
Button('启动服务端')
.onClick(() => {
this.udp.bind({ address: '192.168.3.19', port: 8099 }, err => {
if (err) {
console.error(TAG + ' server bind fail:' + JSON.stringify(err));
}
console.error(TAG + ' server bind success');
});
this.udp.on("message", value => {
this.receiveMessage = this.bufToString(value.message);
console.error(TAG + " server message:" + this.receiveMessage + ", remoteInfo:" + JSON.stringify(value.remoteInfo));
})
})
Text(`收到数据如下:\n ${this.receiveMessage}`)
Button('启动客户端')
.margin({ top: 50 })
.onClick(() => {
this.udp.bind({ address: '192.168.3.19' })
})
Button('点我发送《我是客户端发送的数据》到服务端')
.onClick(() => {
this.udp.send({
data: '我是客户端发送的数据',
address: {
address: '192.168.3.19',
port: 8099
}
}).then(() => {
console.error(TAG + ' client send success');
}).catch(err => {
console.error(TAG + ' client send fail:' + JSON.stringify(err));
});
})
}
.width('100%')
}
.height('100%')
}
bufToString(buf: ArrayBuffer) {
let textDecoder = util.TextDecoder.create('utf-8')
let str = textDecoder.decodeWithStream(new Uint8Array(buf))
return str;
}
}