Harmonyos网络通信真机Demo演练(一)之TCP聊天室

开发 OpenHarmony
本Demo界面由ArkUI实现,网络逻辑部分由java实现,服务器用容易部署演练的Go实现。JAVA和GO初次实战,本Demo还存在并发数据安全未处理,所以本Demo仅能用于学习。

[[439633]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

本Demo界面由ArkUI实现,网络逻辑部分由java实现,服务器用容易部署演练的Go实现。JAVA和GO初次实战,本Demo还存在并发数据安全未处理,所以本Demo仅能用于学习。可学习之处有以下几点:

    一、FA与PA采用ACE方式的调用及相互交互、数据流转等。

    二、Harmonyos的事件机制及使用–自定义事件.

    三、异步多线程TCP通信。

一、效果展示

1,服务器端

#星光计划2.0#Harmonyos网络通信真机Demo演练(一)之TCP聊天室-鸿蒙HarmonyOS技术社区

2,客户端

#星光计划2.0#Harmonyos网络通信真机Demo演练(一)之TCP聊天室-鸿蒙HarmonyOS技术社区

二、设计流程图

#星光计划2.0#Harmonyos网络通信真机Demo演练(一)之TCP聊天室-鸿蒙HarmonyOS技术社区

三、界面编写

1,界面效果

#星光计划2.0#Harmonyos网络通信真机Demo演练(一)之TCP聊天室-鸿蒙HarmonyOS技术社区

2,界面代码

HML代码:

  1. <div class="container"
  2.     <div class="container1"
  3.         <text class="title"
  4.             tcp-client test 
  5.         </text> 
  6.     </div> 
  7.     <div class="container2"
  8.         <text class="text2">IP:</text> 
  9.         <input class="input2" placeholder="enter ip" onchange="onChange2"
  10.         </input> 
  11.     </div> 
  12.     <div class="container3"
  13.         <text class="text3">Port:</text> 
  14.         <input class="input3" placeholder="enter port" onchange="onChange3"
  15.         </input> 
  16.     </div> 
  17.     <button class="button1" type="capsule" onclick="onConnect">连接服务器</button> 
  18.     <button class="button3" type="capsule" onclick="onSubResvMsg">订阅消息</button> 
  19.     <textarea class="text4"
  20.         {{outcont}} 
  21.     </textarea> 
  22.     <div class="container4"
  23.         <input class="input5" placeholder="enter msg" onchange="onChange4"
  24.         </input> 
  25.         <button class="button2" type="capsule" onclick="onSend">发送消息</button> 
  26.     </div> 
  27. </div> 

JS代码:

  1. import prompt from '@system.prompt'
  2.  
  3. export default { 
  4.     data: { 
  5.         title: 'World'
  6.         outcont: ''
  7.         ip:''
  8.         port:''
  9.         msg:'' 
  10.     }, 
  11.  
  12.     initConnectAction: function (code,ip,port) { 
  13.         var actionData = {}; 
  14.         actionData.ip = ip; 
  15.         actionData.port = port; 
  16.         var action = {}; 
  17.         action.bundleName = "com.gane.tcpclient"
  18.         action.abilityName = "TcpClientAbility"
  19.         action.messageCode = code; 
  20.         action.data = actionData; 
  21.         action.abilityType = 1; 
  22.         action.syncOption = 0; 
  23.         return action
  24.     }, 
  25.  
  26.     initAction: function (code) { 
  27.         var actionData = {}; 
  28.         var action = {}; 
  29.         action.bundleName = "com.gane.tcpclient"
  30.         action.abilityName = "TcpClientAbility"
  31.         action.messageCode = code; 
  32.         action.data = actionData; 
  33.         action.abilityType = 1; 
  34.         action.syncOption = 0; 
  35.         return action
  36.     }, 
  37.  
  38.     initAction2: function (code,msg) { 
  39.         var actionData = {}; 
  40.         actionData.msg = msg; 
  41.         var action = {}; 
  42.         action.bundleName = "com.gane.tcpclient"
  43.         action.abilityName = "TcpClientAbility"
  44.         action.messageCode = code; 
  45.         action.data = actionData; 
  46.         action.abilityType = 1; 
  47.         action.syncOption = 0; 
  48.         return action
  49.     }, 
  50.  
  51.  
  52.     onChange2(e){ 
  53.         this.ip = e.value; 
  54.     }, 
  55.  
  56.     onChange3(e){ 
  57.         this.port = e.value; 
  58.     }, 
  59.  
  60.     onConnect: async function() { 
  61.         try { 
  62.             var action = this.initConnectAction(1001,this.ip,this.port); 
  63.             var result = await FeatureAbility.callAbility(action); 
  64.             console.info(" result = " + result); 
  65.             this.showToast(result); 
  66.         } catch (pluginError) { 
  67.             console.error("getBatteryLevel : Plugin Error = " + pluginError); 
  68.         } 
  69.     }, 
  70.  
  71.     onSubResvMsg:async function(){ 
  72.         try { 
  73.             var action = this.initAction(1003); 
  74.             var that = this; 
  75.             var result = await FeatureAbility.subscribeAbilityEvent(action,function (msgdata) { 
  76.                 console.info(" batteryLevel info is: " + msgdata); 
  77.                 var msgRet = JSON.parse(msgdata).data; 
  78.                 that.printData(msgRet.msg); 
  79.                 that.showToast(" batteryState change: " + msgRet.msg); 
  80.             }); 
  81.             this.showToast(" subscribe result " + result); 
  82.             console.info(" subscribeCommonEvent result = " + result); 
  83.         } catch (pluginError) { 
  84.             console.error("subscribeCommonEvent error : result= " + result + JSON.stringify(pluginError)); 
  85.         } 
  86.     }, 
  87.  
  88.     onSend: async function() { 
  89.         try { 
  90.             var action = this.initAction2(1002,this.msg); 
  91.             var result = await FeatureAbility.callAbility(action); 
  92.             console.info("onSend result = " + result); 
  93.             this.showToast(result); 
  94.         } catch (pluginError) { 
  95.             console.error("getBatteryLevel : Plugin Error = " + pluginError); 
  96.         } 
  97.     }, 
  98.  
  99.     onChange4(e){ 
  100.         this.msg = e.value; 
  101.     }, 
  102.  
  103.     printData(msg){ 
  104.         if(this.outcont != null || this.outcont != ""){ 
  105.             this.outcont = msg + "\n" + this.outcont; 
  106.         } else { 
  107.             this.outcont = msg; 
  108.         } 
  109.     }, 
  110.  
  111.     showToast: function (msg) { 
  112.         prompt.showToast({ 
  113.             message: msg 
  114.         }); 
  115.     } 

注意:

  1,这里的交互方法都是用的异步方法,因为这样不会因业务侧而阻塞UI线程,从而阻塞主线程。

  2,仔细看清楚每个initAction(),弄明白action的构造和带参传递的写法。

四、PA编写与交互

java类实现方式如下:

  1. public class TcpClientAbility extends AceInternalAbility { 
  2.     private static final String TAG = TcpClientAbility.class.getSimpleName(); 
  3.     private static final String BUNDLE_NAME = "com.gane.tcpclient"
  4.     private static final String ABILITY_NAME = "TcpClientAbility"
  5.     public static final String SELF_SOCKET_MSG = "TCP.CLIENT.MSG"
  6.     private static TcpClientAbility instance; 
  7.     private TcpClientAbility() { 
  8.         super(BUNDLE_NAME, ABILITY_NAME); 
  9.     } 
  10.  
  11.     /** 
  12.      * ACE注册 
  13.      */ 
  14.     public void register() { 
  15.         this.setInternalAbilityHandler(this::onRemoteRequest); 
  16.         HiLog.error(LABEL_LOG,"socket_register"); 
  17.     } 
  18.  
  19.     /** 
  20.      * ACE取消注册 
  21.      */ 
  22.     public void deregister() { 
  23.         this.setInternalAbilityHandler(null); 
  24.         HiLog.error(LABEL_LOG,"socket_unregister"); 
  25.     } 
  26.     /** 
  27.      * ACE事件回调接口 
  28.      */ 
  29.     public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) { 
  30.         switch (code) { 
  31.         } 
  32.         return true
  33.     } 

注意:

  1,类必须继承AceInternalAbility,必须实现注册、取消注册、事件回调接口。

  2,register()、deregister()需在合适的位置调用,我是在mainAblity的onstart和onstop中调用的

五、TCP客户端网络

网络实现,考虑到要能随时随地的自由发送和接收消息,就将消息的收、发分离,全采用异步进行。根据业务需求选型了AsynchronousSocketChannel作为本次实现的网络基础类型,主要用到了AsynchronousSocketChannel.open()、AsynchronousSocketChannel.setOption()、AsynchronousSocketChannel.connect()、AsynchronousSocketChannel.write()、AsynchronousSocketChannel.read()等接口。

示例代码如下:

  1. socketChannel = AsynchronousSocketChannel.open(); 
  2. socketChannel.setOption(StandardSocketOptions.TCP_NODELAY,true); 
  3. socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); 
  4. socketChannel.connect(new InetSocketAddress(param.getIp(), param.getPort()), null
  5.     new CompletionHandler<Void, Object>() { 
  6.         @Override 
  7.         public void completed(Void result, Object attachment) { 
  8.         ByteBuffer byteBuffer = ByteBuffer.allocate(1024); 
  9.         String intput = "我是:"
  10.         try { 
  11.             intput = intput + socketChannel.getLocalAddress().toString(); 
  12.         } catch (IOException e) { 
  13.             e.printStackTrace(); 
  14.         } 
  15.         try { 
  16.             byteBuffer.put(intput.getBytes("UTF-8")); 
  17.         } catch (UnsupportedEncodingException e) { 
  18.             e.printStackTrace(); 
  19.         } 
  20.         socketChannel.write(byteBuffer, 1, TimeUnit.SECONDS, null
  21.             new CompletionHandler<Integer, Object>() { 
  22.             @Override 
  23.             public void completed(Integer result, Object attachment) { 
  24.             } 
  25.             public void failed(Throwable exc, Object attachment) { 
  26.             } 
  27.         }); 
  28.         } 
  29.  
  30.         @Override 
  31.         public void failed(Throwable exc, Object attachment) { 
  32.         } 
  33.     }); 
  1. if (TcpClientAbility.socketChannel != null && TcpClientAbility.socketChannel.isOpen()) { 
  2.     ByteBuffer byteBuffer = ByteBuffer.allocate(1024); 
  3.     CompletionHandler<Integer, Object> comphandler = new CompletionHandler<Integer, Object>() { 
  4.         @Override 
  5.         public void completed(Integer result, Object attachment) { 
  6.             byteBuffer.flip(); 
  7.             byte[] byten = new byte[byteBuffer.limit()]; // 可用的字节数量 
  8.             byteBuffer.get(byten, byteBuffer.position(), byteBuffer.limit()); 
  9.             String ret = new String(byten); 
  10.             TcpClientAbility.socketChannel.read(byteBuffer, -1, TimeUnit.SECONDS, null, this); 
  11.         } 
  12.         @Override 
  13.         public void failed(Throwable exc, Object attachment) { 
  14.             TcpClientAbility.socketChannel.read(byteBuffer, -1, TimeUnit.SECONDS, null, this); 
  15.             } 
  16.         }; 
  17.     TcpClientAbility.socketChannel.read(byteBuffer, -1, TimeUnit.SECONDS, null, comphandler); 

六、自定义事件

由官方提供的CommonEventManager通用事件启发而来,官方提供了harmonyos系统提供了蓝牙、电池、时间、日期等等相关的通用事件,还提供了电池相关的Demo,具体介绍看官方文档。我这里拿CommonEventManager的CommonEventManager.subscribeCommonEvent()订阅事件、CommonEventManager.publishCommonEvent()发布事件给大家看下:

  1. MatchingSkills matchingSkills = new MatchingSkills(); 
  2. matchingSkills.addEvent(SELF_SOCKET_MSG); 
  3. IRemoteObject notifier = data.readRemoteObject(); 
  4. CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
  5. subscriber = new CommonEventSubscriber(subscribeInfo) { 
  6.     @Override 
  7.     public void onReceiveEvent(CommonEventData commonEventData) { 
  8.         //HiLog.info(LABEL_LOG,"socket===shijian" + commonEventData.getData() + ret); 
  9.             } 
  10.         }; 
  11.         try { 
  12.             CommonEventManager.subscribeCommonEvent(subscriber); 
  13.         } catch (RemoteException e) { 
  14.         } 
  1. Intent intent = new Intent(); 
  2. Operation operation = new Intent.OperationBuilder().withAction(TcpClientAbility.SELF_SOCKET_MSG).build(); 
  3. intent.setOperation(operation); 
  4. intent.setParam("msg",ret); 
  5. CommonEventData eventData = new CommonEventData(intent); 
  6. eventData.setData(ret); 
  7. try { 
  8.     CommonEventManager.publishCommonEvent(eventData); 
  9. } catch (RemoteException e) { 
  10.     e.printStackTrace(); 

七、总结

大概思路和所用到的重点知识点在上面以分别列出来了,做完了觉得很简单,但实际上用一门或多门不怎么熟悉而且相关开发思路借鉴比较少的开发框架写东西时,确实会在动手前很迷茫。觉得迷茫不要退缩,还是那句话,没有程序解决不了的问题,只有没思路的程序员,只要想做,就要将整体拆解,化整为零,个个击破。

本文虽然实现了简单的多客户端自由聊天,但还有很多不足,如聊天记录保存,跳转页面后回来怎么恢复页面,websocket、UDP、HTTP、蓝牙等通信模式的探索实践等,不足之处后续有空继续探索不上。有啥不足之处欢迎大家留言,助我改进提升。

文章相关附件可以点击下面的原文链接前往下载

https://harmonyos.51cto.com/resource/1567

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2021-11-16 09:38:10

鸿蒙HarmonyOS应用

2019-04-29 10:26:49

TCP网络协议网络通信

2022-07-26 14:53:10

WebSocket网络通信协议

2022-12-01 08:25:23

eTsTCP聊天室

2009-08-24 17:20:13

C#网络通信TCP连接

2011-12-15 11:11:51

JavaNIO

2023-02-10 08:16:48

WebSocket简易聊天室

2022-11-14 08:01:48

2019-09-02 10:20:27

TCPIP协议

2024-02-20 19:53:57

网络通信协议

2015-07-06 10:42:18

PHP聊天室应用

2019-09-25 08:25:49

RPC网络通信

2021-02-06 23:26:25

聊天室开发WebSocket

2023-01-05 09:17:58

2023-01-13 00:02:41

2014-09-16 17:00:02

UDP

2020-07-06 07:52:10

Kubernetes网络通信

2022-05-13 10:59:14

容器网络通信

2024-01-18 11:15:46

Pythonsocket聊天室

2011-06-09 15:44:29

Spring
点赞
收藏

51CTO技术栈公众号