1. UDP回聲服務(wù)器簡(jiǎn)介
回聲服務(wù)器指的是這樣一種服務(wù)器,它接受客戶端的連接,并且把收到的數(shù)據(jù)原樣返回給客戶端,本系列的第2篇文章《鴻蒙網(wǎng)絡(luò)編程系列2-UDP回聲服務(wù)器的實(shí)現(xiàn)》中基于ArkTS語(yǔ)言在API 9的環(huán)境下實(shí)現(xiàn)了UDP回聲服務(wù)器,本文將使用倉(cāng)頡語(yǔ)言在API 12的環(huán)境中實(shí)現(xiàn)類似的功能。當(dāng)然,UDP是無(wú)連接的協(xié)議,沒有所謂的服務(wù)端,嚴(yán)格來說,UDP回聲服務(wù)器并不是一個(gè)服務(wù)器,而是一個(gè)UDP客戶端,和普通客戶端不不同的是,作為UDP回聲服務(wù)器的客戶端,不主動(dòng)發(fā)送消息,只是在接收到消息以后,才會(huì)給發(fā)送端回復(fù)同樣的消息。
2. UDP回聲服務(wù)器演示
本示例運(yùn)行后的頁(yè)面如圖所示:

輸入綁定的本地端口,默認(rèn)是9999,單擊“綁定”按鈕即可執(zhí)行綁定,如圖所示:

再啟動(dòng)上一篇文章《鴻蒙網(wǎng)絡(luò)編程系列47-倉(cāng)頡版UDP客戶端》中介紹的UDP客戶端,使用該客戶端連接本UDP服務(wù)器,然后發(fā)送“Hi,Server”給服務(wù)端,如圖所示:

可以看到,收到了服務(wù)端的回復(fù),此時(shí)再查看回聲服務(wù)器的日志,如圖所示:

可以看到,回聲服務(wù)器也收到了客戶端的發(fā)送的消息。
3. UDP回聲服務(wù)器示例編寫
下面詳細(xì)介紹創(chuàng)建該示例的步驟(確保DevEco Studio已安裝倉(cāng)頡插件)。
步驟1:創(chuàng)建[Cangjie]Empty Ability項(xiàng)目。
步驟2:在module.json5配置文件加上對(duì)權(quán)限的聲明:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
這里添加了訪問互聯(lián)網(wǎng)的權(quán)限。
步驟3:在build-profile.json5配置文件加上倉(cāng)頡編譯架構(gòu):
"cangjieOptions": {
"path": "./src/main/cangjie/cjpm.toml",
"abiFilters": ["arm64-v8a", "x86_64"]
}
步驟4:在index.cj文件里添加如下的代碼:
package ohos_app_cangjie_entry
import ohos.base.*
import ohos.component.*
import ohos.state_manage.*
import ohos.state_macro_manage.*
import std.collection.HashMap
import ohos.net.http.*
import ohos.file_picker.*
import ohos.ability.getStageContext
import ohos.ability.*
import ohos.file_fs.*
import std.time.DateTime
import std.convert.*
import std.net.*
import std.socket.*
@Entry
@Component
class EntryView {
@State
var title: String = '倉(cāng)頡版UDP回聲服務(wù)器示例';
//連接、通訊歷史記錄
@State
var msgHistory: String = ''
//本地端口
@State
var localPort: UInt16 = 9999
//綁定狀態(tài)
@State
var bindState = false
let scroller: Scroller = Scroller()
func build() {
Row {
Column {
Text(title).fontSize(14).fontWeight(FontWeight.Bold).width(100.percent).textAlign(TextAlign.Center).
padding(10)
Flex(FlexParams(justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center)) {
Text("綁定的本地端口:").fontSize(14)
TextInput(text: localPort.toString()).onChange({
value => localPort = UInt16.parse(value)
}).setType(InputType.Number).width(100).fontSize(11).flexGrow(1)
Button("綁定").onClick {
evt => bind()
}.enabled(!bindState).width(70).fontSize(14)
}.width(100.percent).padding(10)
Scroll(scroller) {
Text(msgHistory).textAlign(TextAlign.Start).padding(10).width(100.percent).backgroundColor(0xeeeeee)
}.align(Alignment.Top).backgroundColor(0xeeeeee).height(300).flexGrow(1).scrollable(
ScrollDirection.Vertical).scrollBar(BarState.On).scrollBarWidth(20)
}.width(100.percent).height(100.percent)
}.height(100.percent)
}
func bind() {
//UDP服務(wù)端
let udpServer = UdpSocket(bindAt: localPort)
udpServer.bind()
msgHistory += "綁定到端口${localPort}\r\n"
bindState = true
//啟動(dòng)一個(gè)線程讀取客戶端發(fā)送過來的消息
spawn {
try {
//存放從socket讀取數(shù)據(jù)的緩沖區(qū)
let buffer = Array<UInt8>(1024, item: 0)
while (true) {
//從socket讀取數(shù)據(jù)
var recResult = udpServer.receiveFrom(buffer)
let clientAddress = recResult[0]
let readCount = recResult[1]
//把接收到的數(shù)據(jù)轉(zhuǎn)換為字符串
let content = String.fromUtf8(buffer[0..readCount])
//輸出讀取的內(nèi)容,加上前綴S:
msgHistory += "${clientAddress}:${content}\r\n"
udpServer.sendTo(clientAddress, content.toArray())
}
} catch (exp: Exception) {
msgHistory += "從套接字讀取數(shù)據(jù)出錯(cuò):${exp}\r\n"
}
}
}
}
步驟5:編譯運(yùn)行,可以使用模擬器或者真機(jī)。
步驟6:按照本文第2部分“UDP回聲服務(wù)器演示”操作即可。
4. 代碼分析
本示例的關(guān)鍵部分在于接收到客戶端發(fā)送的數(shù)據(jù)后,再解析數(shù)據(jù)并重新發(fā)送給客戶端,代碼如下:
//從socket讀取數(shù)據(jù)
var recResult = udpServer.receiveFrom(buffer)
let clientAddress = recResult[0]
let readCount = recResult[1]
//把接收到的數(shù)據(jù)轉(zhuǎn)換為字符串
let content = String.fromUtf8(buffer[0..readCount])
//輸出讀取的內(nèi)容,加上前綴S:
msgHistory += "${clientAddress}:${content}\r\n"
udpServer.sendTo(clientAddress, content.toArray())
這里面需要注意的是receiveFrom函數(shù)的返回值,和上一篇介紹的receive函數(shù)不同,receive函數(shù)是客戶端使用connect函數(shù)連接到確定的對(duì)端后再讀取數(shù)據(jù),而receiveFrom函數(shù)不需要預(yù)先connect,在返回值里直接包括對(duì)端的地址和接收到的消息長(zhǎng)度。
(本文作者原創(chuàng),除非明確授權(quán)禁止轉(zhuǎn)載)
本文源碼地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/udp/UDPEchoServer4Cj