更新升级 专属应用 系统故障 硬件故障 电脑汽车 鸿蒙刷机 鸿蒙开发Linux教程 鸿蒙开发Linux命令
当前位置:HMXT之家 > 应用开发 > HarmonyOS ARK UI技术之Socket连接的基本使用代码

HarmonyOS ARK UI技术之Socket连接的基本使用代码

更新时间: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%')

  }

}

效果展示

\

运行以上代码后得获得的效果。

相关参考:鸿蒙DevEco中在联网的时候是否需要权限?当前TCP socket连接不上