jay
jay

Reputation: 85

Sending udp message from node js to html

var dgram = require(‘dgram’);
var client = dgram.createSocket(‘udp4’);
var PORT= 69;
var HOST= '192.168.0.136'
var message= new Buffer('hello');


set interval(function() {
client.send(message,0,message.length,PORT, HOST, function (err, bytes) {

});
} , 10000);

client.on('message', function(message) {
var temp = message.toString();
console.log(temp);
});

This is a really quick udp example I made. A udp message 'hello' is sent to a server every 10 second. Then the message received is printed to console. The udp server is set up so that it sends a random number each time any message is received. Rather than printed to the console, I want to emit this message to an html page and print on an html page. Can someone show a quick example where the message would be showcased on an output box in an html page which would update with new message. I have researched and some sources say that websockets can not emit udp packets, but other say otherwise. Please help me clarify this.

Upvotes: 2

Views: 2782

Answers (2)

jay
jay

Reputation: 85

Node js-

  io.on('connection', function(socket){
      client.on('message', function(message){
        var temp= message.toString();
        io.emit('temp', temp);
      });
    });

html -

<script>
var socket = io();
socket.on('temp', function(temp){
  $('#messages').html(temp);
});

include the above code in your node js, the message is received by client.on, then emitted to socket. The html page has a socket listener for any incoming messages.

Upvotes: 1

man
man

Reputation: 155

You can't.
Websockets is a standalone protocol and can't emit raw UDP packets directly.

Upvotes: 0

Related Questions