Giter Site home page Giter Site logo

udp's Introduction

Lightweight UDP library for Dart.

Usage

A simple usage example:

import 'package:udp/udp.dart';


main() async {
    // creates a UDP instance and binds it to the first available network
    // interface on port 65000.
    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) {
      var str = String.fromCharCodes(datagram.data);
      stdout.write(str);
    });
  
    // close the UDP instances and their sockets.
    sender.close();
    receiver.close();
  
  
   // MULTICAST
    var multicastEndpoint =
        Endpoint.multicast(InternetAddress("239.1.2.3"), port: Port(54321));
  
    var receiver = await UDP.bind(multicastEndpoint);
  
    var sender = await UDP.bind(Endpoint.any());
  
    receiver.asStream().listen((datagram) {
      if (datagram != null) {
        var str = String.fromCharCodes(datagram?.data);
  
        stdout.write(str);
      }
    });
  
    await sender.send("Foo".codeUnits, multicastEndpoint);
  
    await Future.delayed(Duration(seconds:5));
  
    sender.close();
    receiver.close();
  
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

udp's People

Contributors

tapanav avatar thunderstorm010 avatar xenoken avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

udp's Issues

Receiving broadcast on Android

I am able to receive udp broadcasts packets on my phone from a flutter app using UDP using the Android app NetPal. (I highly recommend this app for debugging issues network issues on an android.)
I am also able to receive unicast packets using UDP on my Android Flutter app.
However, I am not able receive udp packets that are broadcast with my Flutter app using UDP. My best guess is that I am missing a permission in my manifest.
Any suggestions?

Issue since upgraging with .listen

Hey :)

I get : Error: The method 'listen' isn't defined for the class 'UDP'. since updating my flutter project, have not touched it in a while... now I get this and am confused? It works for linux but not Android...

lib/main.dart:1
: Error: The method 'listen' isn't defined for the class 'UDP'.
lib/nodes.dart:168
- 'UDP' is from 'package:udp/src/udp_base.dart' ('../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/udp-5.0.3/lib/src/udp_base.dart').
package:udp/src/udp_base.dart:1
Try correcting the name to the name of an existing method, or defining a method named 'listen'.
      await socket.listen((datagram) {
                   ^^^^^^

and my code...

var socket = await UDP.bind(Endpoint.any(port: Port(6454)));
    try {
      // receiving\listening
      await socket.listen((datagram) {
        if (nodes.foundDevices[datagram?.address.address] != null) {
.........

Any Ideas? Thanks!

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.

StreamBuilder integration?

Hi there,
This plugin has a .listen(...) API, but this doesn't really fit Flutter's reactive nature. Since a StreamSubscription is used internally for this API, it shouldn't be too hard to expose a stream to be listened to - which would allow easy integration with UIs.

Can this possibly be implemented?

Subnet broadcast is not possible

Sending to Endpoint.broadcast() is equivalent to IPV4 255.255.255.255, but trying to send to a subnet broadcast address (e.g. 192.168.1.255 for a subnet of 255.255.255.0) using Endpoint.unicast() throws permission denied/file descriptor Socket Exceptions on Android.

Directly using RawDatagramSocket allows setting RawDatagramSocket.broadcastEnabled=true which is required for sending to a subnet broadcast address.

  1. Either expose the broadcastEnabled field for the Endpoint.unicast() constructor,
  2. or expose the address field for the Endpoint.broadcast() contructor.

nulticast

is dart udp support multicast video stream?

mutiple requests not work

Im design an app that send a UDP broadcast.
my code is simple send a fixed packet when i click in button. this is the function that is called. nut the problem is that the frist time work, the second show sent X bytes but not receive anything in others devices or response. i check with wireshart and the packet is not sent. sometimes can send 2/3 times but some only the first

searchDevices() async {

var sender = await UDP.bind(Endpoint.any(port: Port.any));
devices=[];

sender.socket?.broadcastEnabled=true;
// send a simple string to a broadcast endpoint on port 65001.

//sender.as

// creates a new UDP instance and binds it to the local address and the port
// 65002.
//var receiver = await UDP.bind(Endpoint.any(port: Port.any));
//receiver.socket?.broadcastEnabled=true;
// receiving\listening
sender.asStream(timeout: Duration(seconds: 5)).listen((datagram) {
  var str = String.fromCharCodes(datagram!.data);
  print(str);
  devices.add(str);

  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text(str)),
  );

  // receiver.close();
});


var dataLength = await sender.send( numbers, Endpoint.broadcast(port: Port(9998)));

print('$dataLength bytes sent.');
//receiver.socket.broadcastEnabled


// close the UDP instances and their sockets.
await Future.delayed(Duration(seconds: 5)); // Wait for responses.

// sender.close();

}

Not able to work with udp on iOS when I run app from xCode

I am using following code to use the udp.

try { UDP? sender = await UDP.bind( Endpoint.any(port: const Port(8888))); } on SocketException catch (ex) { print(ex.message); }

But it always throws exception saying "Failed to create datagram socket"

Do I need extra setup for this to work?

Android receive udp broadcast from other device but fails sending its own broadcast

Hi, I'm trying to send broadcast from Android phone to the network but it fails. Here is the code (the same code works on iOS devices and on Mac). Android device receive the broadcast from that devices, but other devices do not receive its broadcast.
Maybe I'm missing something obvious but I cannot find what.
Thanks in advance, Luca.

In the AndroidManifest I've set the following permissions:




SyncServer({
required int port,
required this.broadcastPort,
required this.onDataReceived,
this.onClientConnected
}) : endpoint = Endpoint.any(port: Port(port));

void start ()
{
broadcaster = UDP.bind(endpoint);
ServerSocket
.bind(endpoint.address, endpoint.port!.value)
.then((ServerSocket socket) {
_socket = socket;
_socket?.listen((client) {
_handleConnection(client);
});
});
}

void broadcast({required bool periodic, Duration? period, required String hiringMessage}) {
broadcaster?.then(
(value) {
final packet = BasePacket(senderName: DeviceInfoService().getName(), command: 'hello', data: hiringMessage);
final dataToSend = packet
.toJson()
.codeUnits;
if (periodic) {
_broadcastTimer = Timer.periodic(
period ?? const Duration(seconds: 1),
(timer) {
value.send(dataToSend, Endpoint.broadcast(port: Port(broadcastPort)));
}
);
}
else {
value.send(dataToSend, Endpoint.broadcast(port: Port(broadcastPort)));
}
}
);
}

HandleUncaughtErrorHandler error:OS Error: Bad file descriptor, errno = 9

Report: type:HandleUncaughtErrorHandler error:OS Error: Bad file descriptor, errno = 9 stackTrace:#0 _NativeSocket.nativeGetOption (dart:io-patch/socket_patch.dart:1693:53)
#1 _NativeSocket.getOption (dart:io-patch/socket_patch.dart:1571:18)
#2 _RawDatagramSocket.broadcastEnabled (dart:io-patch/socket_patch.dart:2493:40)
#3 UDP.send. (package:udp/src/udp_base.dart:113:32)
#4 UDP.send. (package:udp/src/udp_base.dart:112:29)
#5 new Future.microtask. (dart:async/future.dart:276:37)
#6 _rootRun (dart:async/zone.dart:1418:47)
#7 _CustomZone.run (dart:async/zone.dart:1328:19)
#8 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#9 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:1276:23)
#10 _rootRun (dart:async/zone.dart:1426:13)
#11 _CustomZone.run (dart:async/zone.dart:1328:19)
#12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#13 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:1276:23)
#14 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#15 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
extraInfo:null

Hardware communication

How to get the hardware IP by directly connecting the hardware device. Communicate again

[Flutter] [Android] OS Error errno = 1 or 13 when binding in release mode

Issue in flutter android, only in release mode

Sample code:

await UDP.bind(Endpoint.any(port: const Port(65000)));

Exception, in UDP.bind (package:udp/src/udp_base.dart:90):

SocketException: 
  Failed to create datagram socket (OS Error: Operation not permitted, errno = 1),
  address = 0.0.0.0,
  port = 65000

logcat:

--------- beginning of main
02-20 11:06:57.827 12794 12794 E le.udp_sampl: Not starting debugger since process cannot load the jdwp agent.
02-20 11:06:57.929 12794 12794 I ForceDarkHelper: packageName:com.example.udp_sample getForceDarkConfigInfo null  forceDarkAppConfigJsonString:null
--------- beginning of system
02-20 11:06:57.929 12794 12794 I ForceDarkHelper: ForceDarkConfigInfo: null
02-20 11:06:57.934 12794 12794 I MiuiForceDarkConfig: MiuiForceDarkConfig setConfig density:2.750000, mainRule:17, secondaryRule:0, tertiaryRule:0
02-20 11:06:57.937 12794 12794 D NetworkSecurityConfig: No Network Security Config specified, using platform default
02-20 11:06:57.938 12794 12794 D NetworkSecurityConfig: No Network Security Config specified, using platform default
02-20 11:06:58.038 12794 12794 W le.udp_sample: type=1400 audit(0.0:1691132): avc: denied { read } for name="max_map_count" dev="proc" ino=57141474 scontext=u:r:untrusted_app:s0:c123,c257,c512,c768 tcontext=u:object_r:proc_max_map_count:s0 tclass=file permissive=0 app=com.example.udp_sample
02-20 11:06:58.093 12794 12794 D View    : com.example.udp_sample initForcedUseForceDark: 1
02-20 11:06:58.095 12794 12794 E le.udp_sampl: Invalid ID 0x00000000.
02-20 11:06:58.098 12794 12794 I SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl@2bda03b
02-20 11:06:58.115 12794 12794 D DecorView[]: getWindowModeFromSystem  windowmode is 1
02-20 11:06:58.115 12794 12794 D DecorView: createDecorCaptionView windowingMode:1 mWindowMode 1 isFullscreen: true
02-20 11:06:58.140 12794 12794 D ViewRootImpl[MainActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
02-20 11:06:58.141 12794 12794 D DecorView[]: getWindowModeFromSystem  windowmode is 1
02-20 11:06:58.147 12794 12794 I InputTransport: Create ARC handle: 0xd31c2650
02-20 11:06:58.147 12794 12794 V PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@d62f16e, this = DecorView@1c4800f[MainActivity]
02-20 11:06:58.176 12794 12794 D SurfaceView: UPDATE null, mIsCastMode = false
02-20 11:06:58.620 12794 12833 E ion     : ioctl c0044901 failed with code -1: Invalid argument
02-20 11:06:58.731 12794 12818 I le.udp_sampl: ProcessProfilingInfo new_methods=982 is saved saved_to_disk=1 resolve_classes_delay=8000
02-20 11:07:29.071 12794 12826 I GED     : ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 29, oppidx_max 29, oppidx_min 0
02-20 11:07:29.073 12794 12794 V PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@d62f16e, this = DecorView@1c4800f[MainActivity]
02-20 11:07:29.690 12794 12794 V PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@d62f16e, this = DecorView@1c4800f[MainActivity]
02-20 11:07:29.692 12794 12794 V PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@d62f16e, this = DecorView@1c4800f[MainActivity]

Things i tried (unsuccessfully):

  • Port(0), Port.any, other ports > 1024
  • Endpoint.unicast to my router broadcast ip
  • Endpoint.loopback and Endpoint.broadcast

Other androids tests

I tested in two devices, one with android 11, and the other with android 8, the same error is thrown in both, the difference is that in android 8 I get Failed to create datagram socket (OS Error: Permission denied, errno = 13),.

Misc info

It works fine if I run in dev mode with flutter run.
My guess is that is a permission missing? In my android/app/src/profile/AndroidManifest.xml I have:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

Runtime info

Flutter 2.10.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 097d3313d8 (2 days ago) • 2022-02-18 19:33:08 -0600
Engine • revision a83ed0e5e3
Tools • Dart 2.16.1 • DevTools 2.9.2

udp version: 5.0.1

SocketException for iOS

Exception: SocketException: Failed to create datagram socket (OS Error: Can't assign requested address, errno = 49), address = 255.255.255.255, port = 7777

I can't reveive data from server -iPhone

My initialization

 _initUdp() async {
    print("_initUdp");
    // MULTICAST
     multicastEndpoint =
    Endpoint.multicast(InternetAddress("231.0.1.1"), port: Port(21555));
     print(InternetAddress("231.0.1.1").type);

    sender = await UDP.bind(Endpoint.any());
    receiver = await UDP.bind(multicastEndpoint);

    unawaited(receiver.listen((datagram) {
      print("------->upd receive");
      if (datagram != null) {
        var str = String.fromCharCodes(datagram?.data);

        print(str);
      }
    }));
  }

image

flutter: _initUdp
flutter: InternetAddressType: IPv4
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: OS Error: Can't assign requested address, errno = 49
#0      _NativeSocket.nativeJoinMulticast (dart:io-patch/socket_patch.dart:1379:56)
#1      _NativeSocket.joinMulticast (dart:io-patch/socket_patch.dart:1331:5)
#2      _RawDatagramSocket.joinMulticast (dart:io-patch/socket_patch.dart:2127:13)
#3      UDP.bind.<anonymous closure> (package:udp/src/udp_base.dart:87:16)
#4      _rootRunUnary (dart:async/zone.dart:1192:38)
#5      _CustomZone.runUnary (dart:async/zone.dart:1085:19)
#6      _FutureListener.handleValue (dart:async/future_impl.dart:141:18)
#7      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
#8      Future._propagateToListeners (dart:async/future_impl.dart:711:32)

Under Android, everything is normal, you can send data and receive data. Under the iPhone, udp initialization error is reported, as shown above. Under the iPhone, data can be sent, but data cannot be received.

Maybe this article can be help https://www.zhihu.com/question/40986079

Web udp.

Hello. I see that this library not work on web. But how can I send udp broadcast on port and listen the same port?

Can send, but can't receive packets on Android 11

Following code

final receiver = await UDP.bind(Endpoint.broadcast(port: Port(65002)));
receiver!.listen((datagram) {
  // ...
});

Works on Android 10, but doesn't work on Android 11
I'm able to receive only packets that are sen't from the same device using

final sender = sender = await UDP.bind(Endpoint.any(port: Port(65000)));
sender.send(
  msg.codeUnits,
  Endpoint.broadcast(port: Port(65002))
);

How to solve this issue?

Doesn't seem to be working with flutter.

The example code in the example appears to not be working with flutter. First, it denies permission with the ports used in the example (this one is easy to fix, just use high number ports) and mostly, i could not get it to work with a phone and a computer, either of then being the server or the client.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.