鴻蒙網(wǎng)絡(luò)編程系列37-基于TCP套接字的TLS通訊客戶端示例

1. TLS通訊簡介

在本系列的第7、8篇文章,分別講解了基于TLS傳輸單向和雙向認(rèn)證的通訊示例,這兩個示例都是TLS客戶端直接連接TLS服務(wù)端的。眾所周知,TLS通訊也是基于TCP協(xié)議的,首先在TCP協(xié)議上,客戶端和服務(wù)端連接成功,然后雙方經(jīng)過TLS握手過程,認(rèn)證數(shù)字證書,最后再進(jìn)行加密的通訊。既然這樣,能不能先顯式建立TCP連接,然后把這個連接再升級為TLS協(xié)議呢?在鴻蒙的早期版本是不可以的,不過在API 12提供了一個新的函數(shù):

function constructTLSSocketInstance(tcpSocket: TCPSocket): TLSSocket;

通過該函數(shù),可以基于一個已經(jīng)建立連接的TCP套接字生成TLS客戶端,然后不經(jīng)過調(diào)用bind函數(shù),就可以和服務(wù)端建立連接。

本文將通過一個示例演示上述過程,也就是首先建立一個TCP客戶端,然后該客戶端通過TCP協(xié)議和TLS服務(wù)端建立連接,然后再基于該TCP客戶端創(chuàng)建TLS客戶端,在配置好服務(wù)端CA證書后,再和TLS服務(wù)端建立連接,最后進(jìn)行正常的TLS通訊,本示例可以使用在本系列第33篇文章《鴻蒙網(wǎng)絡(luò)編程系列33-TLS回聲服務(wù)器示例》中創(chuàng)建的TLS服務(wù)端,并且需要預(yù)先啟動服務(wù)端。

2. 基于TCP套接字的TLS客戶端演示

本示例運行后的界面如圖所示:


image.png

輸入服務(wù)端地址和端口,,然后單擊“選擇”按鈕選擇服務(wù)端證書的CA證書,最后單擊“連接”按鈕即可連接TLS服務(wù)端,如圖所示:

image.png

通過日志區(qū)域可以看到,首先建立了TCP連接,然后再建立了TLS連接。連接成功后,輸入要發(fā)送的消息,再單擊“發(fā)送”按鈕即可發(fā)送消息給服務(wù)端,如圖所示:

image.png

此時查看服務(wù)端,也可以看到客戶端發(fā)送的消息,如圖所示:

image.png

3. 基于TCP套接字的TLS客戶端示例編寫

下面詳細(xì)介紹創(chuàng)建該示例的步驟。
步驟1:創(chuàng)建Empty Ability項目。
步驟2:在module.json5配置文件加上對權(quán)限的聲明:

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]

這里添加了訪問互聯(lián)網(wǎng)的權(quán)限。
步驟3:在Index.ets文件里添加如下的代碼:

import socket from '@ohos.net.socket';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { picker } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';


@Entry
@Component
struct Index {
  @State title: string = '基于TCP套接字的TLS通訊客戶端示例';
  //連接、通訊歷史記錄
  @State msgHistory: string = ''
  //要發(fā)送的信息
  @State sendMsg: string = ''
  //服務(wù)端IP地址
  @State serverIp: string = "0.0.0.0"
  //服務(wù)端端口
  @State serverPort: number = 9999
  //是否可以發(fā)送消息
  @State canSend: boolean = false
  //選擇的ca文件
  @State caFileUri: string = ''
  tlsSocket: socket.TLSSocket | undefined
  scroller: Scroller = new Scroller()

  build() {
    Row() {
      Column() {
        Text(this.title)
          .fontSize(14)
          .fontWeight(FontWeight.Bold)
          .width('100%')
          .textAlign(TextAlign.Center)
          .padding(10)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("服務(wù)端地址:")
            .fontSize(14)
            .width(90)
            .flexGrow(1)

          TextInput({ text: this.serverIp })
            .onChange((value) => {
              this.serverIp = value
            })
            .width(110)
            .fontSize(12)
            .flexGrow(4)

          Text(":")
            .width(5)
            .flexGrow(0)

          TextInput({ text: this.serverPort.toString() })
            .type(InputType.Number)
            .onChange((value) => {
              this.serverPort = parseInt(value)
            })
            .fontSize(12)
            .flexGrow(2)
            .width(50)
        }
        .width('100%')
        .padding(10)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("服務(wù)端證書CA")
            .fontSize(14)
            .width(90)
            .flexGrow(1)

          Button("選擇")
            .onClick(async () => {
              this.caFileUri = await selectSingleDocFile(getContext(this))
            })
            .width(70)
            .fontSize(14)

          Button("連接")
            .onClick(() => {
              this.connect2Server()
            })
            .width(70)
            .fontSize(14)
        }
        .width('100%')
        .padding(10)

        Text(this.caFileUri)
          .width('100%')

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          TextInput({ placeholder: "輸入要發(fā)送的消息" }).onChange((value) => {
            this.sendMsg = value
          })
            .width(200)
            .flexGrow(1)

          Button("發(fā)送")
            .enabled(this.canSend)
            .width(70)
            .fontSize(14)
            .flexGrow(0)
            .onClick(() => {
              this.sendMsg2Server()
            })
        }
        .width('100%')
        .padding(10)

        Scroll(this.scroller) {
          Text(this.msgHistory)
            .textAlign(TextAlign.Start)
            .padding(10)
            .width('100%')
            .backgroundColor(0xeeeeee)
        }
        .align(Alignment.Top)
        .backgroundColor(0xeeeeee)
        .height(300)
        .flexGrow(1)
        .scrollable(ScrollDirection.Vertical)
        .scrollBar(BarState.On)
        .scrollBarWidth(20)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .height('100%')
    }
    .height('100%')
  }

  //發(fā)送消息到服務(wù)端
  sendMsg2Server() {
    this.tlsSocket?.send(this.sendMsg + "\r\n")
      .then(async () => {
        this.msgHistory += "我:" + this.sendMsg + "\r\n"
      })
      .catch((err: BusinessError) => {
        this.msgHistory += `發(fā)送失?。哄e誤碼 ${err.code}, 錯誤信息 ${JSON.stringify(err)}\r\n`;
      })
  }

  //連接服務(wù)端
  async connect2Server() {
    //服務(wù)端地址
    let serverAddress: socket.NetAddress = { address: this.serverIp, port: this.serverPort, family: 1 }

    let tcpSocket = socket.constructTCPSocketInstance()
    await tcpSocket.connect({ address: serverAddress })
      .then(async () => {
        this.msgHistory += 'TCP連接成功 ' + "\r\n";
      })
      .catch((err: BusinessError) => {
        this.msgHistory += `TCP連接失敗:錯誤碼 ${err.code}, 錯誤信息 ${JSON.stringify(err)}\r\n`;
        return
      })

    //執(zhí)行TLS通訊的對象
    this.tlsSocket = socket.constructTLSSocketInstance(tcpSocket)

    this.tlsSocket.on("message", async (value) => {
      let msg = buf2String(value.message)
      this.msgHistory += "服務(wù)端:" + msg + "\r\n"
      this.scroller.scrollEdge(Edge.Bottom)
    })

    let context = getContext(this)

    let opt: socket.TLSSecureOptions = {
      ca: [copy2SandboxAndReadContent(context, this.caFileUri)]
    }

    await this.tlsSocket.connect({ address: serverAddress, secureOptions: opt })
      .then(async () => {
        this.msgHistory += 'TLS連接成功 ' + "\r\n";
        this.canSend = true
      })
      .catch((err: BusinessError) => {
        this.msgHistory += `TLS連接失?。哄e誤碼 ${err.code}, 錯誤信息 ${JSON.stringify(err)}\r\n`;
      })
  }
}

//選擇一個文件
async function selectSingleDocFile(context: Context): Promise<string> {
  let selectedFilePath: string = ""
  let documentPicker = new picker.DocumentViewPicker(context);
  await documentPicker.select({ maxSelectNumber: 1 }).then((result) => {
    if (result.length > 0) {
      selectedFilePath = result[0]
    }
  })
  return selectedFilePath
}

//復(fù)制文件到沙箱并讀取文件內(nèi)容
function copy2SandboxAndReadContent(context: Context, filePath: string): string {
  let segments = filePath.split('/')
  let fileName = segments[segments.length-1]
  let realUri = context.cacheDir + "/" + fileName
  let file = fs.openSync(filePath);
  fs.copyFileSync(file.fd, realUri)
  fs.closeSync(file)

  return fs.readTextSync(realUri)
}

//ArrayBuffer轉(zhuǎn)utf8字符串
function buf2String(buf: ArrayBuffer) {
  let msgArray = new Uint8Array(buf);
  let textDecoder = util.TextDecoder.create("utf-8");
  return textDecoder.decodeToString(msgArray)
}

步驟4:編譯運行,可以使用模擬器或者真機(jī)。

步驟5:按照本節(jié)第2部分“基于TCP套接字的TLS客戶端演示”操作即可。

4. 代碼分析

本示例關(guān)鍵點在于創(chuàng)建TLS客戶端的過程,首先要創(chuàng)建TCP客戶端并且連接成功,其次才能創(chuàng)建TLS客戶端::

    //服務(wù)端地址
    let serverAddress: socket.NetAddress = { address: this.serverIp, port: this.serverPort, family: 1 }

    let tcpSocket = socket.constructTCPSocketInstance()
    await tcpSocket.connect({ address: serverAddress })
      .then(async () => {
        this.msgHistory += 'TCP連接成功 ' + "\r\n";
      })
      .catch((err: BusinessError) => {
        this.msgHistory += `TCP連接失?。哄e誤碼 ${err.code}, 錯誤信息 ${JSON.stringify(err)}\r\n`;
        return
      })

    //執(zhí)行TLS通訊的對象
    this.tlsSocket = socket.constructTLSSocketInstance(tcpSocket)

另外一點是關(guān)于配置TLS客戶端的服務(wù)端CA證書,選擇證書后需要復(fù)制到沙箱才能讀取文件內(nèi)容,這一點是通過函數(shù)copy2SandboxAndReadContent實現(xiàn)的。

(本文作者原創(chuàng),除非明確授權(quán)禁止轉(zhuǎn)載)

本文源碼地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/tls/TCPBaseTLSClient

本系列源碼地址:
https://gitee.com/zl3624/harmonyos_network_samples

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容