udp
udp copied to clipboard
Example doesnt work
import 'dart:io';
import 'package:udp/udp.dart';
void main() async {
var sender = await UDP.bind(Endpoint.any(port: Port(65000)));
// send a simple string to a broadcast endpoint on port 65001.
var dataLength = await sender.send(
"Hello World!".codeUnits, Endpoint.broadcast(port: Port(65001)));
stdout.write("$dataLength bytes sent.");
// creates a new UDP instance and binds it to the local address and the port
// 65002.
var receiver = await UDP.bind(Endpoint.loopback(port: Port(65002)));
// receiving\listening
receiver.asStream(timeout: Duration(seconds: 20)).listen((datagram) {
print("received something");
var str = String.fromCharCodes(datagram!.data);
stdout.write(str);
});
// close the UDP instances and their sockets.
sender.close();
receiver.close();
}
only output:
12 bytes sent.
I encountered the same problem.
After a few minute's work, I edited the code and this is my code below:
Future<void> udp() async {
var sender = await UDP.bind(Endpoint.loopback(port: const Port(65000)));
// creates a new UDP instance and binds it to the local address and the port
// 65001.
var receiver = await UDP.bind(Endpoint.loopback(port: const Port(65001)));
// receiving\listening
receiver.asStream(timeout: const Duration(seconds: 20)).listen((datagram) {
if (kDebugMode) {
print("received something");
}
var str = String.fromCharCodes(datagram!.data);
if (kDebugMode) {
print(str);
}
});
// send a simple string to a loopback endpoint on port 65001.
var dataLength = await sender.send(
"Hello World!".codeUnits, Endpoint.loopback(port: const Port(65001)));
if (kDebugMode) {
print("$dataLength bytes sent.");
}
// close the UDP instances and their sockets.
// sender.close();
// receiver.close();
}
Output:
flutter: 12 bytes sent.
flutter: received something
flutter: Hello World!
I am using Dart to build Flutter app for both mobile and desktop devices, so I replaced the stdout.write
to print
.
I guess there are three main reasons why the example code doesn't work:
- The port the sender send the data to(65001) was different from the port of receiver(65002).
- The receiver started to listening messages after the sender sent the data. This could cause a data loss.
- The receiver was closed at the end, which may led to a cancellation when receiving data.
We should close the sender and the receiver manually when they finish their work at a suitable time.