I have been programming for 2 months now and I want to make a mobile app, which will comunicate with a server on a PC in the same LAN. I am using NodeJS Dgram module and Socket.io. I am broadcasting messages on a server and I want to see those messages on my mobile device, so that when I start an app on a device, I will listen for messages and then make a socket connection to the address, where the message was sent from. I have seen a couple of examples/solutins on web, but I still do not understand and it just gets me more confused. Currently it works well because I broadcast from one PC and on another PC I run node client.js and then listen for those messages, but I would like to do the same, just on mobile device (Cordova platform).
The goal is that I will click a button and start listening for a broadcast messages if this is even possible.
Code for broadcasting - on the server:
const dgram = require('dgram');
const broadcasts = this.getBroadcastAddresses();
_broadcasting = setInterval(
function (broadcasts, dgram, options) {
broadcasts.forEach(function (broadcast) {
const message = Buffer.from(options.data);
console.log(message);
const client = dgram.createSocket({ type: 'udp4', reuseAddr: true });
client.bind(8080, function () {
client.setBroadcast(true);
client.send(message, 0, message.length, 8080, broadcast, function (err, bytes) {
if (err) {
console.error(err);
}
client.close();
if (options.hasOwnProperty('callback')) {
options.callback(broadcast, err, bytes);
}
return;
});
});
});
},
options.timer * 1000,
broadcasts,
dgram,
options
);
Code for Client to listen for messages:
if (util.platform === 'webkit') {
var dgram = require('dgram');
_socket = socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
_socket.on('message', function (message, rinfo) {
console.log('Message: ' + rinfo.address + ':' + rinfo.port + ' - ' + message);
});
_socket.on('listening', () => {
options.bind_callback(socket.address());
});
_socket.bind(8080, '0.0.0.0');
} else if (util.platform === 'cordova') {
_socket = window.dgram.createSocket('udp4', 8080);
_socket.on('message', (msg, remote) => {
options.message_callback(msg.toString(), remote);
});
_socket.on('listening', () => {
options.bind_callback(socket.address());
});
_socket.bind();
}