Last active
December 13, 2018 11:46
-
-
Save serhatates/0661782aa654f6312c29a808676d6805 to your computer and use it in GitHub Desktop.
Server - Client UDP [node.js]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
======== | |
Client | |
======== | |
*/ | |
const HOST = 'localhost'; | |
const PORT = 41234; | |
var dgram = require('dgram'); | |
var client = dgram.createSocket('udp4'); | |
client.on('message', function (msg, rinfo) { | |
console.log('recieved: ' + msg.toString('hex')); | |
client.close(); | |
}); | |
client.on('err', function (err) { | |
console.log('client error: \n' + err.stack); | |
console.close(); | |
}); | |
client.on('close', function () { | |
console.log('closed.'); | |
}); | |
function send(message, host, port) { | |
client.send(message, 0, message.length, port, host, function (err, bytes) { | |
console.log('sent.'); | |
}); | |
} | |
// var message = new Buffer('hello', 'utf8'); | |
let message = Buffer.from('3031323334353637', 'hex'); | |
send(message, HOST, PORT); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
======== | |
Server | |
======== | |
*/ | |
const PORT = 41234; | |
var dgram = require('dgram'); | |
var server = dgram.createSocket('udp4'); | |
server.on('listening', function () { | |
var address = server.address(); | |
console.log('server listening ' + address.address + ':' + address.port); | |
}); | |
server.on('message', function (msg, rinfo) { | |
console.log('server got a message from ' + rinfo.address + ':' + rinfo.port); | |
console.log(' HEX : ', msg.toString('utf8')); | |
console.log(' ASCII: ', msg); | |
var ack = Buffer.from('ack'); | |
server.send(ack, 0, ack.length, rinfo.port, rinfo.address, function (err, bytes) { | |
console.log('sent ACK.'); | |
}); | |
}); | |
server.on('error', function (err) { | |
console.log('server error: \n' + err.stack); | |
server.close(); | |
}); | |
server.on('close', function () { | |
console.log('closed.'); | |
}); | |
server.bind(PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment