54.HarmonyOS鸿蒙系统 App(ArkTS)tcp socket套接字网络连接

54.HarmonyOS鸿蒙系统 App(ArkTS)tcp socket套接字网络连接

复制代码
import socket from '@ohos.net.socket';
import process from '@ohos.process';
import wifiManager from '@ohos.wifiManager';


import common from '@ohos.app.ability.common';


let tcp = socket.constructTCPSocketInstance();
//let ipAddress = wifiManager.getIpInfo().ipAddress; //真机测试
//let local_ip2 = (ipAddress>>24 &0xFF)+"."+(ipAddress>>16 &0xFF)+"."+(ipAddress>>8 &0xFF)+"."
//+(ipAddress &0xFF) //真机测试
let local_ip2 = '127.0.0.1' //用于模拟器,真机则屏蔽此处

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  @State local_ip:string = local_ip2
  @State local_port:number =6666
  @State ip_addr:string ='192.168.10.104'
  @State port:number =8080
  @State send_msg:string ='send content'
  @State recv_msg:string =''
  
  build() {


      Column() {
        Row(){
          Text(' ')
        }
        Row(){
          Text('TCP socket测试连接')
            .fontSize(38)
            .fontColor(Color.White)
            .backgroundColor(Color.Blue)
        }
        Row(){
          Text('本机IP:').fontSize(28)
            .backgroundColor(Color.Green)
          TextInput({text:`${this.local_ip}`})
            .fontSize(28)
            .width(280)
            .backgroundColor(Color.Transparent)
            .onChange((value:string)=>{
              this.local_ip = value
            })

        }
        Row(){
          Text('端口:').fontSize(28)
            .backgroundColor(Color.Green)
          TextInput({text:`${this.local_port}`})
            .fontSize(28)
            .width(280)
            .backgroundColor(Color.Transparent)
            .onChange((value:string)=>{
              this.local_port = parseInt(value, 10); //字符转数字
            })

        }
        Row(){
          Text('服务器IP:').fontSize(28)
            .backgroundColor(Color.Green)
          TextInput({text:`${this.ip_addr}`})
            .fontSize(28)
            .width(280)
            .backgroundColor(Color.Transparent)
            .onChange((value:string)=>{
              this.ip_addr = value
            })

        }
        Row(){
          Text('端口:').fontSize(28)
            .backgroundColor(Color.Green)
          TextInput({text:`${this.port}`})
            .fontSize(28)
            .width(280)
            .backgroundColor(Color.Transparent)
            .onChange((value:string)=>{
              this.port = parseInt(value, 10); //字符转数字
            })

        }
        Row(){
          Text('发送:').fontSize(28)

        }.align(Alignment.Start)
        Row(){
          TextArea({text:`${this.send_msg}`})
            .fontSize(28)
            .height(100)
            .onChange((value:string)=>{
              this.send_msg = value
            })
        }
        Row(){
          Text('接收:').fontSize(28)

        }.align(Alignment.Start)
        Row(){
          TextArea({text:`${this.recv_msg}`}).fontSize(28) //文本自动换行
            .height(200)
        }
        Row()
        {
          Button('连接')
            .width(100)
            .fontSize(28)
            .onClick(() => {
              // 绑定IP地址和端口。//连接服务器,必须首先绑定本机IP

              let bindAddress = {
                address: this.local_ip,
                port: this.local_port, // 绑定端口,如1234
                family: 1
              };
              tcp.bind(bindAddress, err => {
                if (err) {
                  console.log('bind fail_local');
                  this.recv_msg = 'connect fail_local,IP:'+this.local_ip
                  return;
                }
                 console.log('bind success_local');
                this.recv_msg = 'connect fail_local,IP:'+this.local_ip
              })

              let connectAddress = {
                address: this.ip_addr,
                port: this.port, // 连接端口,如5678
                family: 1
              };
              tcp.connect({
                address: connectAddress, timeout: 3000
              },err=>{
                if (err) {
                  console.log('connect fail_remote');
                  this.recv_msg = 'connect fail_remote,IP:'+this.ip_addr

                  return;
                }
                console.log('connect success');
                this.recv_msg = 'connect success_remote,IP:'+this.ip_addr
              }
              )

          })
          Button('______').onClick((event: ClickEvent) => {
          })
          Button('发送')
            .width(100)
            .fontSize(28)
            .onClick((event: ClickEvent) => {
              tcp.send({
                data: this.send_msg
              }, err => {
                if (err) {
                  console.log('send fail');
                  this.recv_msg='send fail_remote'
                  return;
                }
                console.log('send success');
                this.recv_msg='send success_remote';
              })
          })

        }
        Row(){
          Button('退出')
            .width(100)
            .fontSize(28)
            .onClick((event: ClickEvent) => {
              tcp.close();
              const context = getContext(this) as common.UIAbilityContext;
              context.terminateSelf();
              let applicationContext = context.getApplicationContext();
              // applicationContext.killProcessesBySelf().
              // then((data)=>
              // {console.log('The process running information is:'+ JSON.stringify(data));})
              //   .catch((error)=>{console.error('error:'+ JSON.stringify(error));})
              // process.kill(0, process.pid)
              // process.exit(0)
          })
        }


      }
      .width('100%')
    .padding(20) //边距
    .backgroundColor(Color.Gray)

  }
}

配置权限:

arkts获取真机本机IP:

连接远程服务器,tcp/ip,必须绑定本机IP

相关推荐
小镇敲码人7 小时前
华为CANN框架中HCCL仓库的全面解析:分布式通信的引擎
分布式·华为
王码码20357 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos
Trouvaille ~7 小时前
【Linux】TCP Socket编程实战(一):API详解与单连接Echo Server
linux·运维·服务器·网络·c++·tcp/ip·socket
坚果派·白晓明7 小时前
在鸿蒙设备上快速验证由lycium工具快速交叉编译的C/C++三方库
c语言·c++·harmonyos·鸿蒙·编程语言·openharmony·三方库
小镇敲码人8 小时前
深入剖析华为CANN框架下的Ops-CV仓库:从入门到实战指南
c++·python·华为·cann
科技块儿8 小时前
利用IP查询在智慧城市交通信号系统中的应用探索
android·tcp/ip·智慧城市
极新8 小时前
智启新篇,智创未来,“2026智造新IP:AI驱动品牌增长新周期”峰会暨北京电子商务协会第五届第三次会员代表大会成功举办
人工智能·网络协议·tcp/ip
M158227690558 小时前
TCP转LORA产品说明及应用案例
网络·网络协议·tcp/ip
lbb 小魔仙8 小时前
【HarmonyOS实战】OpenHarmony + RN:自定义 useFormik 表单处理
react native·harmonyos
果粒蹬i8 小时前
【HarmonyOS】DAY7:鸿蒙跨平台 Tab 开发问题与列表操作难点深度复盘
华为·harmonyos