您的位置:首页 > 房产 > 家装 > 鸿蒙笔记--Socket

鸿蒙笔记--Socket

2024/10/6 2:22:53 来源:https://blog.csdn.net/ljt2724960661/article/details/140910802  浏览:    关键词:鸿蒙笔记--Socket

       这一节主要了解鸿蒙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 权限

本地测试如下:

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com