Skip to content

Instantly share code, notes, and snippets.

@z3t0
Created July 26, 2016 16:34
Show Gist options
  • Save z3t0/4b47f71f29de85bc084200835b2829aa to your computer and use it in GitHub Desktop.
Save z3t0/4b47f71f29de85bc084200835b2829aa to your computer and use it in GitHub Desktop.
var client = require('./client.js')('127.0.0.1', 3000);
client.sendMessage("new_player");
var dgram = require('dgram')
module.exports = function(host, port) {
return new Client(host, port);
}
function Client(host, port)
{
this.client = dgram.createSocket('udp4');
this.port = port;
this.host = host;
this.init();
}
Client.prototype.init = function() {
this.client.on('listening', () => {
var address = this.client.address();
console.log(`client listening to ${address.host}:${address.port}`);
})
this.client.on('message', function(message,remote) {
this.gotMessage(message, remote);
});
}
Client.prototype.gotMessage = function(message, remote) {
console.log(`Got message "${message}" from "${remote.address}:${remote.port}"`);
}
Client.prototype.sendMessage = function (msg) {
var message = new Buffer(msg);
this.client.send(message, 0, message.length, this.port, this.host, function (err, bytes) {
if(err) throw err;
console.log("UDP message sent to " + this.host + ":" + this.port);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment