43 lines
1015 B
Dart
43 lines
1015 B
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:udp/udp.dart';
|
|
|
|
class UdpService {
|
|
Future<bool> sendPackage({
|
|
required String data,
|
|
required String ipAddress,
|
|
required int port,
|
|
}) async {
|
|
UDP? sender;
|
|
try {
|
|
// Create UDP instance
|
|
sender = await UDP.bind(Endpoint.any());
|
|
|
|
// Convert data to bytes
|
|
final dataBytes = utf8.encode(data);
|
|
|
|
// Parse IP address
|
|
final address = InternetAddress(ipAddress);
|
|
|
|
// Create endpoint
|
|
final destination = Endpoint.unicast(address, port: Port(port));
|
|
|
|
// Send the packet
|
|
final bytesSent = await sender.send(dataBytes, destination);
|
|
|
|
// Give a small delay to ensure packet is sent
|
|
await Future.delayed(const Duration(milliseconds: 100));
|
|
|
|
return bytesSent > 0;
|
|
} catch (e) {
|
|
// Error occurred while sending UDP package
|
|
return false;
|
|
} finally {
|
|
// Always close the socket
|
|
sender?.close();
|
|
}
|
|
}
|
|
}
|
|
|
|
|