Harmony TCP Client

示例代码:

import socket from '@ohos.net.socket';
import wifiManager from '@ohos.wifiManager';


import {resolveIP} from '../common/utils/Utils'
import hilog from '@ohos.hilog';
import connection from '@ohos.net.connection';


let localAddress = resolveIP(wifiManager.getIpInfo().ipAddress);
let localPort = 8085;

@Entry
@Component
struct TestTcpPage {
  @State message: string = 'Hello World'
  @State recvMessage:string=''
  private strInput:string = ""
  private TcpSocket:socket.TCPSocket=null

  tcpInit(){
    this.TcpSocket = socket.constructTCPSocketInstance();
    let localAddresspara = {
      address:localAddress,
      family:1,
      port:0
    }

    this.TcpSocket.bind(localAddresspara)
      .then(()=>{
      hilog.info(0x0000,'TestTag','connected successfully')
    })
      .catch(err=>{
        hilog.info(0x0000,'TestTag',JSON.stringify(err))
        return
      })

    this.TcpSocket.on('connect',()=>{
      this.message = '连接中'
    })
    this.TcpSocket.on('message',(value)=>{
        this.recvMessage = this.resolveArrayBuffer(value.message)


    })
  }

  connectSocket(){
    this.TcpSocket.getState()
      .then((data)=>{
        if(data.isClose)
        {
          this.tcpInit()
        }
        let targetAddresspara = {
          address:'192.168.100.101',
          family:1,
          port:8081
        };
        if(data.isConnected)
        {
          this.recvMessage = '已经连接成功';
        }
        else {
          this.TcpSocket.connect({address:targetAddresspara})
            .then(()=>{
              this.recvMessage = '连接成功';
            })
            .catch(err=>{
              this.recvMessage = '连接失败';
            })
        }


      })
      .catch(error=>{
        this.recvMessage = JSON.stringify(error);
      })

  }

  sendMessage(message: string) {
    this.TcpSocket.getState()
      .then((data) => {
        if (data.isConnected) {
          this.TcpSocket.send({ data: message })
            .then(() => {
              //sucessful
            })
            .catch(err => {
              //send error
            })
        }
        else {
          this.connectSocket()
        }
      })
  }

  resolveArrayBuffer(message:ArrayBuffer):string{
    if(message instanceof ArrayBuffer)
    {
      let dataView = new DataView(message);
      let str="";
      for(let i = 0; i<dataView.byteLength; i++)
      {
        let c = String.fromCharCode(dataView.getUint8(i));
        if(c!='\n')
        {
          str+=c;
        }
      }

      return str;
    }
  }

  aboutToAppear(){
    this.tcpInit();
  }

  build() {

      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold).height('10%')

        Row(){
          Text('请输入内容:').width('50%')
          TextInput().onChange((value:string)=>{
            this.strInput = value;
          }).width('50%')
        }.height('10%')
        Row(){
          Button('连接')
            .onClick((event)=>{
              this.connectSocket()
            }).width('50%')
          Button('发送')
            .onClick((event)=>{
              this.recvMessage = "发送数据:"+this.strInput;
              this.sendMessage(this.strInput)
            }).width('50%')
        }.height('10%')

        Text(){
          Span(this.recvMessage)
        }
      }
      .width('100%').height('100%')

  }
}

Uitls.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);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值