更新时间:2022-05-08 10:21:46浏览次数:465+次
本文介绍鸿蒙HarmonyOS ARK UI技术之Socket连接的基本使用,附源代码及所产生的效果截图。在鸿蒙文档中,有Socket连接的介绍,有兴趣的可以先行阅读一下。
代码实现
import socket from '@ohos.net.socket';
@Entry
@Component
struct SocketPage {
build() {
Row() {
Column() {
Text( '启动服务端')
.fontSize(30)
.backgroundColor(Color.Red)
.width('80%')
.height(80)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let udp = socket.constructUDPSocketInstance();
udp.bind({ address: 'localhost', port: 8088 }, err =>{
if (err){
console.log('server bind fail:' + JSON.stringify(err));
}
console.log('server bind success');
});
udp.on("message", value =>{
console.log("server message:" + value.message + ", remoteInfo:" + JSON.stringify(value.remoteInfo));
})
})
Text( '启动客户端')
.fontSize(30)
.width('80%')
.height(80)
.margin({top : 50})
.fontWeight(FontWeight.Bold)
.onClick(() => {
let udp = socket.constructUDPSocketInstance();
//TODO 如果bind 则send fail:{"code":22},反之send fail:{"code":88}
udp.bind({address:'localhost'})
let send = udp.send({
data: 'Hello, server!',
address: {
address: 'localhost',
port : 8088
}
})
send.then(() => {
console.log('client send success');
}).catch(err => {
console.log('client send fail:' + JSON.stringify(err));
});
udp.on("message", value =>{
console.log("client message:" + value.message + ", remoteInfo:" + JSON.stringify(value.remoteInfo));
})
})
}
.width('100%')
}
.height('100%')
}
}
效果展示
运行以上代码后得获得的效果。
相关资讯