知识补充
简介
套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议栈进行交互的接口,支持TCP/UDP/TLS协议。
基本概念
- Socket:套接字,就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。
- TCP:传输控制协议。是一种面向连接的、可靠的、基于字节流的传输层通信协议。
- UDP:用户数据报协议协议。是一个简单的面向消息的传输层,不需要连接。
- TLS:安全传输层协议。用于在两个通信应用程序之间提供保密性和数据完整性
搭建前端界面
新建项目
等待环境初始化
打开实时预览
前端基本实现效果
@Entry
@Component
struct Index {@State message: string = '本地UDP通信'@State value:string = 'null'build() {Column(){Text(this.message).fontSize(30).fontWeight(FontWeight.Bold).margin({top:10,bottom:50})Row(){Text("发送信息"){}TextInput({placeholder:"输入要发送的内容"}).width('80%')}.width('80%')Button("发送").width('50%').margin({top:10,bottom:50})Row(){Text("接收的信息 ")Text(""){Span(this.value).fontColor(Color.Green).fontSize(30)} // 用于显示所接受UDPServer的消息}.width('80%')}.width('100%').height('100%')}
}
主要代码
创建UDP
async createUDP()
{this.udpSocket=socket.constructUDPSocketInstance() // 创建UDP Socket对象this.udpSocket.bind({address:this.address, // 绑定的IPfamily:1 // 网络协议类型})
}
Socket连接信息
参数名 | 类型 | 说明 |
---|---|---|
address | string | 绑定的IP地址 |
family | string | 网络协议类型(IPv4或IPv6 默认为IPv4) |
port | number | 端口号:0~65535 |
size | number | 服务器响应信息的字节长度 |
关闭UDP
async closeUDP():Promise<void>{await this.udpSocket.close() // 关闭连接this.udpSocket.off('message') // 关闭订阅
this.udpSocket=null // 赋null值
}
发送数据
async sendData(data:string,address:string,port:number):Promise<void>{let option={address:{address:address,port:port,family:1
},data:data
}this.udpSocket.send(option)
}
添加onAppear事件
当组件显示时触发此回调
.onAppear(()=>{this.createUDP() // 创建udpSocket对象this.udpSocket.on('message',(data)=>{ // 订阅消息let dataView=new DataView(data.message)let value=''for(let i=0;i<dataView.byteLength;++i){value+=String.fromCharCode(dataView.getUint8(i))}this.value=value})
})
添加onAppear事件
.onDisAppear(()=>{this.closeUDP()
})
添加控件事件
TextInput({placeholder:"输入要发送的内容"}).width('80%').onChange(value=>{this.outValue=value})
// 当文本框中数值改变将内容存储到变量中
Button("发送").width('50%').margin({top:10,bottom:50}).onClick(()=>{if(this.outValue!='') // 判断发送的值是否为空this.sendData(this.sendValue,this.address,this.port) // 发送数据
})
对程序进行签名
选择自动签名,一个月好像限制签名150次
添加网络权限
"requestPermissions": [{"name": "ohos.permission.INTERNET"},
],
使用SocketTool进行测试
创建一个UDPServer
开启本地模拟机,运行测试
初次连接,程序会自动给UDPServer发送一条UDP connection successful 信息
手动发送信息
UDP Server回复信息
整体代码
import socket from '@ohos.net.socket'
@Entry
@Component
struct Index {@State message: string = '本地UDP通信'@State sendValue:string = '' // 输入框中要发送的值@State saveValue:string = 'Hi' // 存储UDPServer发送的信息@State address:string = '172.16.30.134' // 连接的IP地址@State port:number = 9999 // 连接的端口号private udpSocket:socket.UDPSocket = null // udp变量async createUDP(){this.udpSocket=socket.constructUDPSocketInstance() // 创建UDP Socket对象this.udpSocket.bind({address:this.address, // 绑定的IPfamily:1 // 网络协议类型})}async closeUDP():Promise<void>{await this.udpSocket.close() // 关闭连接this.udpSocket.off('message') // 关闭订阅this.udpSocket=null // 赋null值}async sendData(data:string,address:string,port:number):Promise<void>{let option={address:{address:address,port:port,family:1},data:data}this.udpSocket.send(option)}build() {Column(){Text(this.message).fontSize(30).fontWeight(FontWeight.Bold).margin({top:10,bottom:50})Row(){Text("发送信息"){}TextInput({placeholder:"输入要发送的内容"}).width('80%').onChange(value=>{this.sendValue=value}) // 当文本框中数值改变将内容存储到变量中}.width('80%')Button("发送").width('50%').margin({top:10,bottom:50}).onClick(()=>{if(this.sendValue!='') // 判断发送的值是否为空this.sendData(this.sendValue,this.address,this.port) // 发送数据})Row(){Text("接收的信息 ")Text(""){Span(this.saveValue).fontColor(Color.Green).fontSize(30)}}.width('80%')}.width('100%').height('100%').onAppear(()=>{this.createUDP() // 创建udpSocket对象// this.sendData("UDP connection successful",this.address,this.port)this.udpSocket.on('message',(data)=>{let buffer=data.messagelet dataView=new DataView(buffer)let str=""for (let i =0;i<dataView.byteLength;++i){str+=String.fromCharCode(dataView.getUint8(i))}this.saveValue=str})}).onDisAppear(()=>{this.closeUDP()})}
}