socket API可以参考这个:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-socket.md
推荐大家试用 3.2beta版本来做socket通信,版本下载:
http://ci.openharmony.cn/dailys/dailybuilds
这里提供一个简单的socket通信代码:
import socket from '@ohos.net.socket'
import wifi from '@ohos.wifi';
function resolveIP(ip) {
if (ip < 0 || ip > 0xFFFFFFFF) {
throw ("The number is not normal!");
}
return (ip >>> 24) + "." + (ip >> 16 & 0xFF) + "." + (ip >> 8 & 0xFF) + "." + (ip & 0xFF);
}
let udp = socket.constructUDPSocketInstance()
let port = 3861
let localAddr = {
address: resolveIP(wifi.getIpInfo().ipAddress),
port: port
}
let mixerAddr = {
address: '192.168.255.78',
port: port
}
udp.bind(localAddr, e => {
if (e) {
console.log('==bind error')
return
}
console.log('==bind ok')
})
udp.on('listening', () => {
console.log("==on listening success");
})
udp.on('message', data => {
console.log("==on message!")
let dataView = new DataView(data.message)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
let c = String.fromCharCode(dataView.getUint8(i))
if (c !== "n") {
str += c
}
}
console.log("==message:" + str + "From:" + data.remoteInfo.address)
mixerAddr.address = data.remoteInfo.address
udp.send({ data: 'recv ok!rn',address: mixerAddr});
})
setTimeout(() => {
udp.send({ data: 'hello!rn',address: mixerAddr});
}, 5 * 1000);
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('send', { type: ButtonType.Normal, stateEffect: true })
.onClick(() => {
this.sendData()
})
}
.width('100%')
}
.height('100%')
}
async sendData() {
let order = 'hellorn'
try {
await udp.send({ data: order,address: mixerAddr})
console.log(`==Send ${order} >: + ${mixerAddr.address}`)
} catch (e){
console.log('==Error send: ' + e)
}
}
}
|