当前位置:   article > 正文

鸿蒙Socket通信示例(TCP通信)

鸿蒙Socket通信示例(TCP通信)

前言

DevEco Studio版本:4.0.0.600

参考链接:OpenHarmony Socket

效果

TCPSocket

1、bind绑定本地IP地址

  1. private bindTcpSocket() {
  2. let localAddress = resolveIP(wifi.getIpInfo().ipAddress)
  3. console.info("111111111 localAddress: " + localAddress);
  4. //bind本地地址
  5. tcpSocket.bind({ address: localAddress })
  6. .then(() => {
  7. console.info("111111111 绑定Tcp成功");
  8. })
  9. .catch(err => {
  10. console.info("111111111 绑定Tcp失败,原因: " + err);
  11. });
  12. }

2、设置tcpSocket的监听

  1. private tcpSocketListener() {
  2. tcpSocket.on('connect', () => {
  3. this.connectMessage = '已连接'
  4. console.info("111111111 监听: 连接成功");
  5. });
  6. tcpSocket.on('message', (value: {
  7. message: ArrayBuffer,
  8. remoteInfo: socket.SocketRemoteInfo
  9. }) => {
  10. this.messageReceive = this.messageReceive + this.resolveArrayBuffer(value.message) + "\n"
  11. console.info("111111111 接收服务器的数据: " + this.messageReceive);
  12. });
  13. tcpSocket.on('close', () => {
  14. this.connectMessage = '未连接'
  15. console.info("111111111 监听:关闭连接")
  16. });
  17. }

3、连接服务器

  1. private tcpSocketConnect() {
  2. //开始连接
  3. tcpSocket.connect({
  4. address: { address: connectAddress.address, port: connectAddress.port, family: connectAddress.family },
  5. timeout: 6000
  6. }).then(() => {
  7. console.info("111111111 tcpSocketConnect:连接成功");
  8. let tcpExtraOptions: socket.TCPExtraOptions = {
  9. keepAlive: true, //是否保持连接。默认为false
  10. OOBInline: true, //是否为OOB内联。默认为false
  11. TCPNoDelay: true, //TCPSocket连接是否无时延。默认为false
  12. socketLinger: {
  13. on: true,
  14. linger: 10
  15. }, //socket是否继续逗留。- on:是否逗留(true:逗留;false:不逗留)。- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。当入参on设置为true时,才需要设置。
  16. receiveBufferSize: 1000, //接收缓冲区大小(单位:Byte),默认为0
  17. sendBufferSize: 1000, //发送缓冲区大小(单位:Byte),默认为0
  18. reuseAddress: true, //是否重用地址。默认为false
  19. socketTimeout: 3000//套接字超时时间,单位毫秒(ms),默认为0
  20. }
  21. tcpSocket.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
  22. if (err) {
  23. console.log('111111111 setExtraOptions 失败');
  24. return;
  25. }
  26. console.log('111111111 setExtraOptions 成功');
  27. });
  28. }).catch((error) => {
  29. console.info("111111111 tcpSocketConnect 连接失败,原因: " + JSON.stringify(error));
  30. })
  31. }

4、发送数据内容

  1. private sendMessage() {
  2. tcpSocket.getState().then((data) => {
  3. console.info("111111111 连接状态: " + JSON.stringify(data))
  4. //已连接
  5. if (data.isConnected) {
  6. //发送消息
  7. tcpSocket.send({ data: `${this.inputContent}\n`, encoding: 'UTF-8' })
  8. .then(() => {
  9. this.messageReceive = this.messageReceive + "发送:" + this.inputContent + "\n"
  10. console.info("111111111 消息发送成功");
  11. })
  12. .catch((error) => {
  13. console.info("111111111 消息发送失败,原因:" + JSON.stringify(error));
  14. })
  15. } else {
  16. console.info("111111111 没有连接");
  17. this.connectMessage = '未连接,服务器断了'
  18. }
  19. })
  20. }

5、结束释放资源

  1. private tcpSocketRelease() {
  2. tcpSocket.off("message")
  3. tcpSocket.off("connect")
  4. tcpSocket.off("close")
  5. tcpSocket.close()
  6. tcpSocket = null
  7. }

6、UI实现

  1. build() {
  2. Column() {
  3. TextInput({ placeholder: '请输入用户名', text: '测试数据:Test' })
  4. .width('100%')
  5. .margin({ top: 20, bottom: 20 })
  6. .onChange((value: string) => {
  7. this.inputContent = value
  8. })
  9. Button('发送数据')
  10. .width('100%')
  11. .margin({ top: 20, bottom: 20 })
  12. .onClick(() => {
  13. this.sendMessage()
  14. })
  15. Text() {
  16. Span('连接状态:')
  17. Span(this.connectMessage).fontColor(Color.Red)
  18. }
  19. Scroll() {
  20. Column() {
  21. Text() {
  22. Span('内容:\n')
  23. Span(this.messageReceive).fontColor(Color.Pink)
  24. }
  25. }.width('100%')
  26. .alignItems(HorizontalAlign.Start)
  27. }
  28. .width("100%")
  29. .alignSelf(ItemAlign.Start)
  30. .flexShrink(1)
  31. .margin({ top: 15 })
  32. }
  33. .alignItems(HorizontalAlign.Start)
  34. .padding({ left: 15, right: 15 })
  35. .width('100%')
  36. .height('100%')
  37. }

详细代码

1、Index.ets

  1. import socket from '@ohos.net.socket';
  2. import wifi from '@ohos.wifi';
  3. import { BusinessError } from '@ohos.base';
  4. import { resolveIP } from '../utils/IpUtil';
  5. import util from '@ohos.util';
  6. //tcp连接对象
  7. let tcpSocket = socket.constructTCPSocketInstance();
  8. //连接服务器的地址和端口
  9. let connectAddress = {
  10. address: '10.65.XX.XX', //要通信的 PC地址,CMD--->ipconfig查看
  11. family: 1,
  12. port: 6666
  13. }
  14. @Entry
  15. @Component
  16. struct Index {
  17. @State connectMessage: string = '未连接'
  18. @State messageReceive: string = ''
  19. @State inputContent: string = ''
  20. aboutToAppear() {
  21. this.tcpSocketListener()
  22. this.bindTcpSocket()
  23. }
  24. onPageShow() {
  25. this.tcpSocketConnect()
  26. }
  27. onPageHide() {
  28. this.tcpSocketRelease()
  29. }
  30. build() {
  31. Column() {
  32. TextInput({ placeholder: '请输入用户名', text: '测试数据:Test' })
  33. .width('100%')
  34. .margin({ top: 20, bottom: 20 })
  35. .onChange((value: string) => {
  36. this.inputContent = value
  37. })
  38. Button('发送数据')
  39. .width('100%')
  40. .margin({ top: 20, bottom: 20 })
  41. .onClick(() => {
  42. this.sendMessage()
  43. })
  44. Text() {
  45. Span('连接状态:')
  46. Span(this.connectMessage).fontColor(Color.Red)
  47. }
  48. Scroll() {
  49. Column() {
  50. Text() {
  51. Span('内容:\n')
  52. Span(this.messageReceive).fontColor(Color.Pink)
  53. }
  54. }.width('100%')
  55. .alignItems(HorizontalAlign.Start)
  56. }
  57. .width("100%")
  58. .alignSelf(ItemAlign.Start)
  59. .flexShrink(1)
  60. .margin({ top: 15 })
  61. }
  62. .alignItems(HorizontalAlign.Start)
  63. .padding({ left: 15, right: 15 })
  64. .width('100%')
  65. .height('100%')
  66. }
  67. /**
  68. * tcp连接状态和消息监听
  69. */
  70. private tcpSocketListener() {
  71. tcpSocket.on('connect', () => {
  72. this.connectMessage = '已连接'
  73. console.info("111111111 监听: 连接成功");
  74. });
  75. tcpSocket.on('message', (value: {
  76. message: ArrayBuffer,
  77. remoteInfo: socket.SocketRemoteInfo
  78. }) => {
  79. this.messageReceive = this.messageReceive + this.resolveArrayBuffer(value.message) + "\n"
  80. console.info("111111111 接收服务器的数据: " + this.messageReceive);
  81. });
  82. tcpSocket.on('close', () => {
  83. this.connectMessage = '未连接'
  84. console.info("111111111 监听:关闭连接")
  85. });
  86. }
  87. /**
  88. * 绑定Tcp本地地址
  89. * bind的IP为'localhost'或'127.0.0.1'时,只允许本地回环接口的连接,即服务端和客户端运行在同一台机器上
  90. */
  91. private bindTcpSocket() {
  92. let localAddress = resolveIP(wifi.getIpInfo().ipAddress)
  93. console.info("111111111 localAddress: " + localAddress);
  94. //bind本地地址
  95. tcpSocket.bind({ address: localAddress })
  96. .then(() => {
  97. console.info("111111111 绑定Tcp成功");
  98. })
  99. .catch(err => {
  100. console.info("111111111 绑定Tcp失败,原因: " + err);
  101. });
  102. }
  103. /**
  104. * 发送消息数据
  105. */
  106. private sendMessage() {
  107. tcpSocket.getState().then((data) => {
  108. console.info("111111111 连接状态: " + JSON.stringify(data))
  109. //已连接
  110. if (data.isConnected) {
  111. //发送消息
  112. tcpSocket.send({ data: `${this.inputContent}\n`, encoding: 'UTF-8' })
  113. .then(() => {
  114. this.messageReceive = this.messageReceive + "发送:" + this.inputContent + "\n"
  115. console.info("111111111 消息发送成功");
  116. })
  117. .catch((error) => {
  118. console.info("111111111 消息发送失败,原因:" + JSON.stringify(error));
  119. })
  120. } else {
  121. console.info("111111111 没有连接");
  122. this.connectMessage = '未连接,服务器断了'
  123. }
  124. })
  125. }
  126. /**
  127. * 连接服务器
  128. */
  129. private tcpSocketConnect() {
  130. //开始连接
  131. tcpSocket.connect({
  132. address: { address: connectAddress.address, port: connectAddress.port, family: connectAddress.family },
  133. timeout: 6000
  134. }).then(() => {
  135. console.info("111111111 tcpSocketConnect:连接成功");
  136. let tcpExtraOptions: socket.TCPExtraOptions = {
  137. keepAlive: true, //是否保持连接。默认为false
  138. OOBInline: true, //是否为OOB内联。默认为false
  139. TCPNoDelay: true, //TCPSocket连接是否无时延。默认为false
  140. socketLinger: {
  141. on: true,
  142. linger: 10
  143. }, //socket是否继续逗留。- on:是否逗留(true:逗留;false:不逗留)。- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。当入参on设置为true时,才需要设置。
  144. receiveBufferSize: 1000, //接收缓冲区大小(单位:Byte),默认为0
  145. sendBufferSize: 1000, //发送缓冲区大小(单位:Byte),默认为0
  146. reuseAddress: true, //是否重用地址。默认为false
  147. socketTimeout: 3000//套接字超时时间,单位毫秒(ms),默认为0
  148. }
  149. tcpSocket.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
  150. if (err) {
  151. console.log('111111111 setExtraOptions 失败');
  152. return;
  153. }
  154. console.log('111111111 setExtraOptions 成功');
  155. });
  156. }).catch((error) => {
  157. console.info("111111111 tcpSocketConnect 连接失败,原因: " + JSON.stringify(error));
  158. })
  159. }
  160. /**
  161. * 解析ArrayBuffer
  162. */
  163. private resolveArrayBuffer(message: ArrayBuffer): string {
  164. let view = new Uint8Array(message);
  165. let textDecoder = util.TextDecoder.create()
  166. let str = textDecoder.decodeWithStream(view);
  167. console.info("111111111 message 缓存内容: " + str)
  168. return str;
  169. }
  170. /**
  171. * 关闭Socket监听和连接,释放资源
  172. */
  173. private tcpSocketRelease() {
  174. tcpSocket.off("message")
  175. tcpSocket.off("connect")
  176. tcpSocket.off("close")
  177. tcpSocket.close()
  178. tcpSocket = null
  179. }
  180. }

2、IpUtil.ets

  1. export function resolveIP(ip: number): string {
  2. if (ip < 0 || ip > 0xFFFFFFFF) {
  3. throw ('The number is not normal!');
  4. }
  5. return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
  6. }

3、module.json5配置

因为涉及到网络访问,需要配置网络权限,在module.json5中配置

  1. "requestPermissions": [
  2. {
  3. "name": "ohos.permission.INTERNET" //联网
  4. },
  5. {
  6. "name": "ohos.permission.GET_NETWORK_INFO" //获取网络相关信息
  7. },
  8. {
  9. "name": "ohos.permission.SET_NETWORK_INFO" //设置网络相关信息
  10. },
  11. {
  12. "name": "ohos.permission.GET_WIFI_INFO" //获取wifi相关信息
  13. }
  14. ]

服务器端Java代码

  1. package org.example;
  2. import java.io.*;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. public class SocketService {
  6. public static void main(String[] args) {
  7. int port = 6666;
  8. try {
  9. // 创建ServerSocket对象,指定监听的端口号
  10. ServerSocket serverSocket = new ServerSocket(port);
  11. while (true) {
  12. Socket clientSocket = serverSocket.accept();
  13. System.out.println("客户端连接: " + clientSocket.getInetAddress().getHostAddress());
  14. BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  15. PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
  16. String message;
  17. while ((message = reader.readLine()) != null) {
  18. System.out.println("从客户端接收到的消息: " + message);
  19. writer.println("回复: " + message);
  20. }
  21. reader.close();
  22. writer.close();
  23. clientSocket.close();
  24. System.out.println("连接断开");
  25. }
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }

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

闽ICP备14008679号