Reputation: 11
I'd like to build a HTTP to UDP Gateway. Background is sending UDP Packets triggered with HTTP/AJAX. I started building a Project with Node.js.
I have a working HTTP Server and can send UDP Packages with Node.js. But I cannot send UDP Packages within the http.request-function
. Below is an excerpt of my code:
var http = require('http');
var port = 3000;
var http_server = http.createServer()
http_server.on('request', (request, response) => {
console.log('Request: '+ request.url);
//var message = request.url;
var message = 'test';
var udp_client = dgram.createSocket('udp4');
udp_client.send(message, 0, message.length, 27994, '10.119.233.11', function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
console.log(err);
});
response.end('done');
});
Why is this not working? Any workarounds? Is there in general an easier way to realise my task?
Upvotes: 1
Views: 180
Reputation: 3459
Your particular example doesn't work: you need to define HOST, PORT, import the dgram package... Here's a version that works:
var http = require('http');
var dgram = require('dgram');
var udp_client = dgram.createSocket('udp4');
var server = http.createServer()
server.listen(8080)
server.on('request', (request, response) => {
console.log('Request: '+ request.url);
var message = 'test';
udp_client.send(message, 0, message.length, 27994, '10.119.233.11', function(err, bytes) {
if (err) throw err;
});
response.end('done');
});
Upvotes: 1