当前位置:   article > 正文

鸿蒙笔记--Socket

鸿蒙笔记--Socket

       这一节主要了解鸿蒙Socket通信,在鸿蒙系统中,Socket TCP通讯是一种常用的网络通信方式,它提供了可靠的、面向连接的数据传输服务。它主要用到@ohos.net.socket这个库;

  1. constructTCPSocketInstance:创建一个 TCPSocket;
  2. connect:连接目标服务器;
  3. bind:绑定端口;
  4. send:发送数据;
  5. close:关闭连接;
  6. on:打开对应事件的监听;
  7. off:关闭对应事件的监听;

栗子:

  1. export default class SocketUtils {
  2. public static connect(host: string, mPort: number,data:string) {
  3. let socketTcp = socket.constructTCPSocketInstance();
  4. let localAddress = {
  5. address: host,
  6. family: 1,
  7. port: mPort
  8. }
  9. let tcpOptions = {
  10. address:localAddress,
  11. timeout:15000
  12. }
  13. console.log("connect >>>> tcpOptions:"+JSON.stringify(tcpOptions));
  14. let promise = socketTcp.connect(tcpOptions)
  15. promise.then(() => {
  16. console.log(" connect >>>> ok ");
  17. sendSocketData(socketTcp,data)
  18. }).catch(err => {
  19. console.log(" connect >>>> err:"+JSON.stringify(err));
  20. })
  21. }
  22. }
  23. function sendSocketData(socketTcp: socket.TCPSocket, data: string) {
  24. let options ={
  25. data:JSON.stringify(data)
  26. }
  27. socketTcp.send(options,(err,data) => {
  28. if(err) {
  29. console.log(" sendSocketData >>>> err:"+JSON.stringify(err));
  30. } else {
  31. console.log(" sendSocketData >>>> success data :"+JSON.stringify(data));
  32. }
  33. })
  34. socketTcp.on("message",(message)=> {
  35. const content = StringUtils.arrayBuffer2String(message.message)
  36. console.log(" sendSocketData >>>> message content:"+content);
  37. })
  38. }
  39. import util from '@ohos.util';
  40. class StringUtils {
  41. string2Uint8Array1(value: string): Uint8Array {
  42. if (!value) return null;
  43. //
  44. let textEncoder = new util.TextEncoder();
  45. //获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码
  46. return textEncoder.encodeInto(value)
  47. }
  48. uint8Array2String(input: Uint8Array) {
  49. let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
  50. return textDecoder.decodeWithStream(input, { stream: false });
  51. }
  52. arrayBuffer2String(input: ArrayBuffer) {
  53. return this.uint8Array2String(new Uint8Array(input))
  54. }
  55. }
  56. export default new StringUtils()

注:发起 http 网络请求需要申请 ohos.permission.INTERNET 权限

本地测试如下:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/934675
推荐阅读
  

闽ICP备14008679号