赞
踩
这一节主要了解鸿蒙Socket通信,在鸿蒙系统中,Socket TCP通讯是一种常用的网络通信方式,它提供了可靠的、面向连接的数据传输服务。它主要用到@ohos.net.socket这个库;
- constructTCPSocketInstance:创建一个 TCPSocket;
- connect:连接目标服务器;
- bind:绑定端口;
- send:发送数据;
- close:关闭连接;
- on:打开对应事件的监听;
- off:关闭对应事件的监听;
栗子:
- export default class SocketUtils {
-
- public static connect(host: string, mPort: number,data:string) {
- let socketTcp = socket.constructTCPSocketInstance();
- let localAddress = {
- address: host,
- family: 1,
- port: mPort
- }
- let tcpOptions = {
- address:localAddress,
- timeout:15000
- }
- console.log("connect >>>> tcpOptions:"+JSON.stringify(tcpOptions));
-
- let promise = socketTcp.connect(tcpOptions)
- promise.then(() => {
- console.log(" connect >>>> ok ");
- sendSocketData(socketTcp,data)
- }).catch(err => {
- console.log(" connect >>>> err:"+JSON.stringify(err));
- })
-
- }
- }
-
- function sendSocketData(socketTcp: socket.TCPSocket, data: string) {
- let options ={
- data:JSON.stringify(data)
- }
- socketTcp.send(options,(err,data) => {
- if(err) {
- console.log(" sendSocketData >>>> err:"+JSON.stringify(err));
- } else {
- console.log(" sendSocketData >>>> success data :"+JSON.stringify(data));
- }
- })
-
- socketTcp.on("message",(message)=> {
- const content = StringUtils.arrayBuffer2String(message.message)
- console.log(" sendSocketData >>>> message content:"+content);
- })
- }
-
- import util from '@ohos.util';
- class StringUtils {
- string2Uint8Array1(value: string): Uint8Array {
- if (!value) return null;
- //
- let textEncoder = new util.TextEncoder();
- //获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码
- return textEncoder.encodeInto(value)
- }
- uint8Array2String(input: Uint8Array) {
- let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
- return textDecoder.decodeWithStream(input, { stream: false });
- }
-
- arrayBuffer2String(input: ArrayBuffer) {
- return this.uint8Array2String(new Uint8Array(input))
- }
- }
- export default new StringUtils()
-
-
注:发起 http 网络请求需要申请 ohos.permission.INTERNET 权限
本地测试如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。