Capacitor UDP
UDP Plugin for Capacitor inspired from cordova-plugin-chrome-apps-sockets-udp! Support both IPv6 and IPv4, multicast and broadcast!
For debugging, check out the Udper app developed using this plugin! https://play.google.com/store/apps/details?id=xyz.chenzhongkai.udper&hl=en_US
With capacitor, it is possible to write following code:
{ try await UdpPlugin; let info = await UdpPlugin; await UdpPlugin await UdpPlugin ) } catch //........ }
Isn't it amazing!
Install
$ npm install capacitor-udp
For android development, don't forget to add the plugin class in the MainActivity!
TypeScript Special Mention!!!
declare module '@capacitor/core'
sometimes fail to work as expected. I guess the dirty solution like changing the core-plugin-definitions.ts might be the most trust-worthy solution.
For instance,
;;}
Usage
;const UdpPlugin = Plugins;; // if you want support for converting between ArrayBuffer and String
For intellisense or typescript, you might need to edit the file in @capacitor/core/dist/esm/core-plugin-definitions.ts. Make sure that this file is actually loaded, since there might be other node_modules folders.
API Reference
The api is to some extent similar to Chrome UDP API , but with the taste of capacitor!
- create
- update
- bind
- send
- close
- closeAllSockets
- setBroadcast
- getSockets
- joinGroup
- leaveGroup
- getJoinedGroups
- setPaused
- setMulticastLoopbackMode
Events:
Create
Create a socket for udp, and you can create more than one differentiated by the socket id.
UdpPlugin;
Update
Update the socket info including socket name and buffer size.
UdpPlugin
Bind
You need to bind a socket before sending and receiving data.
UdpPlugin
Send
Capacitor doesn't support Arraybuffer for now, so I need to convert ArrayBuffer to base64 string. I have provided a util function to help you achieve that!
UdpPlugin // bufferString is of type stringUdpPlugin // data is of type ArrayBuffer
Close
Close one socket
UdpPlugin
Close All Sockets
UdpPlugin
Set Broadcast
After enabling broadcasting, you can send data with target address 255.255.255.255.
UdpPlugin
Get Sockets
Obtain all the sockets available.
UdpPlugin
Join Group
Join a particular group address. For IPv4, it's like "238.12.12.12". For IPv6, it's like "ff02::08".
UdpPlugin
Leave Group
UdpPlugin
Get Joined Groups
UdpPlugin
Set Paused
Pause receiving data.
UdpPlugin
Set Multicast Loopback Mode
UdpPlugin
Receive Event
UdpPlugin;
For understanding ArrayBuffer, you can refer to Typed Arrays
Receive Error Event
UdpPlugin;