initial upload
This commit is contained in:
42
lib/services/udp_service.dart
Normal file
42
lib/services/udp_service.dart
Normal file
@ -0,0 +1,42 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user