我想創建一個廣播一些資料的 UDP 套接字,然后監聽來自任意數量設備的回應 5 秒(為簡單起見,一些支持多個回應的代碼已被洗掉)。下面的代碼按預期廣播并按預期接收回應,但它永遠不會超時并且似乎永遠在監聽。我認為該timeout函式只會設定套接字的超時時間,但它似乎什么都不做,除了回傳一個Stream<RawSocketEvent>似乎沒有幫助的實體,除非我錯過了一些東西。
import 'dart:async';
import 'dart:convert';
import 'dart:io';
Future <void> sendData() async {
List<int> buffer = utf8.encode('foobar');
RawDatagramSocket s = await RawDatagramSocket.bind(InternetAddress('192.168.1.123'), 0); // My PC's IP
s.broadcastEnabled = true;
// A call to `timeout` returns an instance of `Stream<RawSocketEvent>`, so I
// don't expect this to do anything the way I have it implemented, but a
// timeout of 5 seconds on the listen is what I'm trying to accomplish.
s.timeout(Duration(seconds: 5));
var subscription = s.listen((RawSocketEvent e) async {
Datagram? dg = s.receive();
if (dg != null) {
print('Received:');
print(utf8.decode(dg.data));
}
});
s.send(buffer, InternetAddress('255.255.255.255'), 1234);
await subscription.asFuture<void>(); // Never gets past here
s.close();
}
Future<void> main() async {
await sendData();
exit(0);
}
我已經對此代碼嘗試了幾種變體,但我總是得到兩個結果之一;listen永遠不會超時,或者main在套接字上接收到任何資料之前回傳(但send成功)。
uj5u.com熱心網友回復:
仍然不清楚為什么該timeout函式沒有按預期設定超時,或者為什么await subscription.asFuture<void>()我的 OP 不起作用,但下面的更改似乎確實有效:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
Future <void> sendData() async {
List<int> buffer = utf8.encode('foobar');
RawDatagramSocket s = await RawDatagramSocket.bind(InternetAddress('192.168.1.123'), 0); // My PC's IP
s.broadcastEnabled = true;
s.listen((RawSocketEvent e) {
Datagram? dg = s.receive();
if (dg != null) {
print('Received:');
print(utf8.decode(dg.data));
}
});
s.send(buffer, InternetAddress('255.255.255.255'), 1234);
await Future.delayed(Duration(seconds: 5)).then((value) {
s.close();
});
}
main() async {
await sendData();
exit(0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/525375.html
標籤:镖插座UDP
下一篇:Go中的HTTP請求驗證中間件
