目录

How do I convert the received object data to ArrayBuffer after a TCPSocket connection is established?

After a TCPSocket connection is established, you can convert received object data to strings and use the following method to convert the strings to ArrayBuffer. The sample code is as follows:

interface ObjData {
  A1: string,
  B1: number,
  C1: ObjData2
}
interface ObjData2 {
  key1: string,
  key2: string
}

@Entry
@Component
export  struct ObjectToArrayBuffer {
  @State message: string = 'Object to ArrayBuffer';

  strToArrayBuffer(str: string) {
    let buf = new ArrayBuffer(str.length * 2);
    let bufView = new Uint16Array(buf);
    for (let i = 0,  strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return bufView;
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let objData: ObjData = {
              A1:'String', 
              B1: 1,
              C1:{'key1':'FF','key2':'GG'}
            }
            let buf1 = this.strToArrayBuffer(JSON.stringify(objData));
            console.info(`buf1: ${JSON.stringify(buf1 )}`);
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}