udp服务信号是如何发送和接收

udp服务信号是如何发送和接收

HarmonyOS
2024-03-19 14:57:28
2743浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
落月无痕

1. import需要的socket模块。

2. 创建一个UDPSocket连接,返回一个UDPSocket对象。

3. 绑定IP地址和端口,端口可以指定或由系统随机分配。

4. 连接到指定的IP地址和端口。

5. 发送数据。

6. socket连接使用完毕后,主动关闭。

参考代码如下:

import { socket }  from '@kit.NetworkKit'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
 
class SocketInfo { 
  message: ArrayBuffer = new ArrayBuffer(1); 
  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 
} 
let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 
let messageView = ''; 
// 订阅UDPSocket连接的接收消息事件 
udp.on('message', (value: SocketInfo) => { 
  for (let i: number = 0; i < value.message.byteLength; i++) { 
    let uint8Array = new Uint8Array(value.message)  
    let messages = uint8Array[i] 
    let message = String.fromCharCode(messages); 
    messageView += message; 
  } 
  console.log('on message message: ' + JSON.stringify(messageView)); 
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 
}); 
// 绑定本地IP地址和端口。 
let bindAddr: socket.NetAddress = { 
  address: '192.168.xx.xxx', 
  port: 1234 
} 
udp.bind(bindAddr, (err: BusinessError) => { 
  if (err) { 
    console.log('bind fail'); 
    return; 
  } 
  let sendOptions: socket.UDPSendOptions = { 
    data: 'Hello, server!', 
    address: { 
      address: '192.168.xx.xxx', 
      port: 8080 
    } 
  } 
  // 发送数据 
  udp.send(sendOptions, (err: BusinessError) => { 
    if (err) { 
      console.log('send fail'); 
      return; 
    } 
    console.log('send success'); 
  }); 
  console.log('bind success'); 
}); 
 
// 关闭连接 
udp.close((err: BusinessError) => { 
  if (err) { 
    console.log('close fail'); 
    return; 
  } 
  console.log('close success'); 
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.

参考链接

Socket连接

分享
微博
QQ
微信
回复
2024-03-19 23:01:09
相关问题
HarmonyOS 发送event接收不到
689浏览 • 1回复 待解决
webview如何进行消息的发送以及接收
1327浏览 • 1回复 待解决
ws库发送过快是否会阻塞接收
2834浏览 • 1回复 待解决
HarmonyOS 如何调用手机发送邮件服务
1021浏览 • 1回复 待解决
如何判断蜂窝信号强度
2741浏览 • 1回复 待解决
HarmonyOS 如何获取信号强度等信息
1283浏览 • 1回复 待解决