#鸿蒙通关秘籍#如何在HarmonyOS NEXT中实现WebSocket客户端的基本通信功能

HarmonyOS
2024-12-05 14:47:33
957浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
SSD风绘长空

在HarmonyOS NEXT中,实现WebSocket客户端通信,需要按照以下步骤创建和配置应用:

  1. 创建Empty Ability项目:启动HarmonyOS IDE,创建一个新的Empty Ability项目。

  2. 配置权限:在module.json5文件中添加访问互联网的权限声明:

    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
  3. 实现WebSocket客户端功能:在Index.ets文件中,导入WebSocket模块,并编写WebSocket客户端通信逻辑:

    import webSocket from '@ohos.net.webSocket';
    
    let wsSocket = webSocket.createWebSocket();
    
    @Entry
    @Component
    struct Index {
      @State msgHistory: string = '';
      @State sendMsg: string = '';
      @State wsServerUrl: string = "ws://192.168.100.100:8081/websocket";
      @State canConnect: boolean = false;
      @State canSend: boolean = false;
      scroller: Scroller = new Scroller();
      eventHandleBinded:boolean=false;
    
      bindEventHandle() {
        if(this.eventHandleBinded) {
          return;
        }
        wsSocket.on('open', (err, value) => {
          this.msgHistory += "连接打开: status:" + value['status'] + ", message:" + value['message'] + "\r\n";
          this.scroller.scrollEdge(Edge.Bottom);
        });
        wsSocket.on('message', (err, value) => {
          this.msgHistory += "服务端: " + value + "\r\n";
          this.scroller.scrollEdge(Edge.Bottom);
        });
        wsSocket.on('error', (err) => {
          this.msgHistory += "出现异常: " + JSON.stringify(err) + "\r\n";
          this.scroller.scrollEdge(Edge.Bottom);
        });
        this.eventHandleBinded = true;
      }
    
      build() {
        Row() {
          Column() {
            Text("WebSocket通讯示例")
              .fontSize(14)
              .fontWeight(FontWeight.Bold)
              .width('100%')
              .textAlign(TextAlign.Center)
              .padding(10);
    
            Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
              Text("服务端url:").fontSize(12).width(70).flexGrow(0);
              TextInput({ text: this.wsServerUrl }).onChange((value) => { this.wsServerUrl = value; }).width(110).fontSize(11).flexGrow(1);
              Button("连接").onClick(() => { this.connect2Server(); }).width(60).fontSize(14).flexGrow(0);
            }.width('100%').padding(10);
    
            Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
              TextInput({ placeholder: "输入要发送的消息" }).onChange((value) => { this.sendMsg = value; }).width(200).flexGrow(1);
              Button("发送").enabled(this.canSend).width(60).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%');
      }
    
      sendMsg2Server() {
        wsSocket.send(this.sendMsg + "\r\n")
          .then((value) => { this.msgHistory += "我:" + this.sendMsg + "\r\n"; })
          .catch((e) => { this.msgHistory += '发送失败' + e.message + "\r\n"; });
      }
    
      connect2Server() {
        this.bindEventHandle();
    
        wsSocket.connect(this.wsServerUrl)
          .then((value) => {
            this.msgHistory += 'connect success ' + "\r\n";
            this.canSend = true;
          })
          .catch((e) => {
            this.msgHistory += 'connect fail ' + e.message + "\r\n";
          });
      }
    }
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
    • 22.
    • 23.
    • 24.
    • 25.
    • 26.
    • 27.
    • 28.
    • 29.
    • 30.
    • 31.
    • 32.
    • 33.
    • 34.
    • 35.
    • 36.
    • 37.
    • 38.
    • 39.
    • 40.
    • 41.
    • 42.
    • 43.
    • 44.
    • 45.
    • 46.
    • 47.
    • 48.
    • 49.
    • 50.
    • 51.
    • 52.
    • 53.
    • 54.
    • 55.
    • 56.
    • 57.
    • 58.
    • 59.
    • 60.
    • 61.
    • 62.
    • 63.
    • 64.
    • 65.
    • 66.
    • 67.
    • 68.
    • 69.
    • 70.
    • 71.
    • 72.
    • 73.
    • 74.
    • 75.
    • 76.
    • 77.
    • 78.
    • 79.
    • 80.
    • 81.
    • 82.
  4. 运行应用:编译并运行应用,可以选择使用模拟器或真实设备进行测试。连接到WebSocket服务器后,即可发送和接收消息。

分享
微博
QQ
微信
回复
2024-12-05 17:37:30


相关问题
HarmonyOS 客户端拖拽效果如何实现
834浏览 • 1回复 待解决
golang redis客户端连接状态
3411浏览 • 1回复 待解决
客户端开发无法获取code
1094浏览 • 1回复 待解决