Dart - 发送 UDP 广播 [英] Dart - Send an UDP broadcast
问题描述
我正在寻求帮助,因为我似乎找不到使用 Dart 在本地网络内发送 UDP 广播的方法.
I'm asking for help since it seems I cannot find a way to send an UDP broadcast inside a local network using Dart.
到目前为止,我设法使用 UDP 与 RawDatagramSocket
进行通信.我可以向特定地址发送消息.
So far I managed to communicate using UDP with RawDatagramSocket
. I'm able to send a message to a specific address.
我无法做的是向本地网络内的任何设备发送广播(网络掩码为 255.255.255.0),并等待可能的(多个)答案.这是我正在使用的代码:
What I'm not able to do is to send a broadcast to any device inside a local network (network mask is 255.255.255.0), and to wait for possible (multiple) answer(s). Here is the code I'm using:
RawDatagramSocket.bind('127.0.0.1', 8889)
.then((RawDatagramSocket udpSocket) {
udpSocket.listen((e) {
Datagram dg = udpSocket.receive();
if (dg != null) {
//stuff
}
});
udpSocket.send(utf8.encode('TEST'), DESTINATION_ADDRESS, 8889);
});
我尝试用 InternetAddress.anyIPv4
替换 DESTINATION_ADDRESS
,但我没有运气.我还在 RawDatagramSocket
中找到了属性 broadcastEnabled
,但我找不到有关如何使用它的更多信息.
I tried to replace DESTINATION_ADDRESS
with InternetAddress.anyIPv4
, but I had no luck. I also found the property broadcastEnabled
inside RawDatagramSocket
, but I cannot find further informations about how to make use of it.
预先感谢您的帮助.
推荐答案
有两个问题:
使用
InternetAddress.anyIPv4
在所有网络接口上进行绑定;
Use
InternetAddress.anyIPv4
for binding on all network interfaces;
使用属性broadcastEnabled
启用广播权限
显然使用广播地址:对于 /24
网络使用 x.y.z.255
地址.
Obviously use a broadcast address: for a /24
network use x.y.z.255
address.
此代码段有效:
import 'dart:io';
import 'dart:convert';
main() {
var DESTINATION_ADDRESS=InternetAddress("x.y.z.255");
RawDatagramSocket.bind(InternetAddress.anyIPv4, 8889).then((RawDatagramSocket udpSocket) {
udpSocket.broadcastEnabled = true;
udpSocket.listen((e) {
Datagram dg = udpSocket.receive();
if (dg != null) {
print("received ${dg.data}");
}
});
List<int> data =utf8.encode('TEST');
udpSocket.send(data, DESTINATION_ADDRESS, 8889);
});
}
这篇关于Dart - 发送 UDP 广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!