A directory service built ontop of udp to allow for p2p service discovery on a local network.
npm install udp-directory-service
To test the sample, start it one or more times with an argument of server, and one or more times with an argument of client.
The server publishes the fact it is providing "My Fantastic Service - Version 1.0.0" and we get it's IP address and any data it has to give us.
//All options can be left out, this shows them being explicitly set to their defaults.//You may wish to allow the user to change the IP and Port used, in case another application already uses this IP and port//There is no need to worry about other people using this library clashing with you, providing you have different service names.var directoryService =port:41834ip:"184.108.40.206" //Must match 220.127.116.11/8socketType:"udp4"logLevel:2includeSelf:false;ifprocessargv2 === "server"//If on the server, publish our service.directoryService;else if processargv2 === "client"//Subscribe to a list of services to see what's availabledirectoryService;
The interesting thing is that two applications can share a UDP port, so this app can co-exist on the same machine multiple times, as well as on separate machines.
If you don't want to see devices on the same machine, you can make use of the getLocalIP method as follows:
//Replace client code withdirectoryService;
You can use this IP method for any other purpose you see fit as well.
Depending on your aplication you may want to include services you publish in what you get back as a subscription. To do this, just set the option includeSelf to false.
Publish a service with the name serviceName. It is good practice to include a version number so only compatible machines will talk to each other. The serviceData is optional and can be any JSON serialisable data. It is made available to clients as part of the subscription.
Subscribe to a service with a service name. Every time the available hosts change, the callback will be notified by being given a list of currently available hosts. Each host has an ip property and a data property.
An object containing arrays of hosts for all currently available services.
gets the local ip address by sending a udp packet and then seeing where it came from when it returns. This may end up being called multiple times for multiple network adapters or just once for a single adaptor (it could do with improving and is subject to change).