鸿蒙UDP

具体文档地址

import socket from '@ohos.net.socket';

let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}).then(() => {
  console.log('bind success');

  udp.getState().then(data => {
    console.log('getState success:' + JSON.stringify(data));
  }).catch(err => {
    console.log('getState fail');
  });

  // https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/js-apis-socket-0000001477981433-V2#ZH-CN_TOPIC_0000001523808874__setextraoptions
  // udp.setExtraOptions({
  //   receiveBufferSize:1000,
  //   sendBufferSize:1000,
  //   reuseAddress:false,
  //   socketTimeout:6000,
  //   broadcast:true
  // }, err=> {
  //   if (err) {
  //     console.log('setExtraOptions fail');
  //     return;
  //   }
  //   console.log('setExtraOptions success');
  // })

}).catch(err => {
  console.log('bind fail');
});

udp.send({
  data:'Hello, server!',
  address: {
    address:'192.168.xx.xxx',
    port:1234,
    family:1
  }
}).then(() => {
  console.log('send success');
}).catch(err => {
  console.log('send fail');
});

// 订阅UDPSocket连接的接收消息事件
udp.on('message', value => {
  console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
});


// let callback = value =>{
//   console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
// }
// udp.on('message', callback);
// // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
// udp.off('message', callback);
// udp.off('message');


// https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/js-apis-socket-0000001477981433-V2#ZH-CN_TOPIC_0000001523808874__onlistening--close
udp.on('listening', () => {
  console.log("on listening success");
});
udp.on('close', () => {
  console.log("on close success" );
});

// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
// udp.off('listening', callback1);
// udp.off('listening');


// udp.on('error', err => {
//   console.log("on error, err:" + JSON.stringify(err))
// });
//
// // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
// udp.off('error', callback);
// udp.off('error');




// let promise = udp.close();
// promise.then(() => {
//   console.log('close success');
// }).catch(err => {
//   console.log('close fail');
// });

确实利好前端

### HarmonyOS UDP Chat Room Implementation Developing a chat room based on the HarmonyOS platform using UDP involves several key components, including network programming with UDP sockets, message handling, and user interface design. Below is an explanation of how this could be implemented. #### Key Concepts UDP (User Datagram Protocol) provides a lightweight mechanism for sending messages without establishing connections beforehand. This makes it suitable for applications where speed is more important than reliability[^1]. In contrast to TCP-based protocols like SIP or WebSocket, which require connection setup and teardown phases, UDP allows direct data transmission between peers after initial configuration. For implementing a chat application under HarmonyOS: 1. **Network Communication**: Utilize UDP socket APIs provided by HarmonyOS's networking libraries. ```cpp int sockfd; struct sockaddr_in servaddr; // Create UDP socket if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = INADDR_ANY; sendto(sockfd, (const char *)message.c_str(), strlen(message.c_str()), MSG_CONFIRM, (const struct sockaddr *)&servaddr, sizeof(servaddr)); ``` 2. **Message Handling**: Implement logic to handle incoming packets efficiently while maintaining state across multiple users participating in the chat session. Logging mechanisms similar to those described might help debug issues during development[^2]. 3. **Concurrency Management**: Since chats involve simultaneous interactions among participants, multi-threaded approaches may enhance performance when managing numerous concurrent sessions effectively[^3]. 4. **UI Design Considerations**: For front-end developers familiar primarily with web technologies rather than native mobile apps, leveraging frameworks compatible both visually appealing interfaces alongside robust backend functionalities becomes crucial[^4]. By integrating these aspects into your project plan carefully considering trade-offs associated each choice made throughout process you'll successfully create functional yet efficient udp-based harmony os chatting solution!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值