UDP multi broadcast nodejs - javascript

I'm trying to create a UDP multi broadcast based chat program, the idea being that anyone on the local network can just pop on and start typing and sending messages.
I figure that every client needs two sockets, one to send messages and one to receive messages.
At its simplest, this is what I have now:
"using strict";
const multicast_addr = "224.1.1.1",
bin_addr = "0.0.0.0",
port = 6811;
var udp = require("dgram");
var listener = udp.createSocket("udp4"),
sender = udp.createSocket("udp4");
listener.bind(port, multicast_addr, function(){
listener.addMembership(multicast_addr);
listener.setBroadcast(true);
});
listener.on("message", function (b, other) {
console.log(b.toString().trim());
});
process.stdin.on("data", function (data){
sender.send(data, 0, data.length, port, multicast_addr);
});
(Never mind the echo, that's application logic that will be built on top)
This will echo the message back to the person running the code, but I also ran this at the same time on a linux VM on the same machine, OS X, but didn't see the messages being passed at all.
I'm not sure if that means that
1) My code is incorrect
2) VMs have the same networking as their host machine?
3) Code is correct but my home router is blocking multi broadcast packets?

Ah, I found this neat trick of reusing ports for addresses.
"using strict";
const multicast_addr = "224.1.1.1",
bin_addr = "0.0.0.0",
port = 6811;
var udp = require("dgram");
var listener = udp.createSocket({type:"udp4", reuseAddr:true}),
sender = udp.createSocket({type:"udp4", reuseAddr:true});
listener.bind(port, multicast_addr, function(){
listener.addMembership(multicast_addr);
listener.setBroadcast(true);
});
listener.on("message", function (b, other) {
console.log(b.toString().trim());
});
process.stdin.on("data", function (data){
sender.send(data, 0, data.length, port, multicast_addr);
});
Worked for having OS X talk to Non-VM Ubuntu over local network.

Related

How can I send data to a specific socket?

My problem is that the current solution I have for sending a specific socket using the library "ws" with node.js is not good enough.
The reason is because if I connect with multiple tabs to the websocket server with the same userid which is defined on the client-side, it will only refer to the latest connection with the userid specified.
This is my code:
// Server libraries and configuration
var server = require("ws").Server;
var s = new server({ port: 5001});
// An array which I keep all websockets clients
var search = {};
s.on("connection", function(ws, req) {
ws.on("message", function(message){
// Here the server process the user information given from the client
message = JSON.parse(message);
if(message.type == "userinfo"){
ws.personName = message.data;
ws.id = message.id;
// Defining variable pointing to the unique socket
search[ws.id] = ws;
return;
}
})
})
As you can see, each time a socket with same id connects, it will refer to the latest one.
Example If you did not understand:
Client connect to server with ID: 1337
search[1337] defined as --> websocket 1
A new connection with same ID: 1337
search[1337] becomes instead a variable refering to websocket 2 instead
Websockets provide a means to create a low-latency network "socket" between a browser and a server.
Note that the client here is the browser, not a tab on a browser.
If you need to manage multiple user sessions between the browser and server, you'll need to write code to do it yourself.

get data from mqtt broker -6lbr

I followed this tutorial :
Running the CC26xx Contiki Examples
but instead of using the cc26xx-demo I used the cc26xx-web-demo and successfully manged to get everything up and running and I can access the 6lbr web page, when I access the sensorTag page I see a mqtt configuration page as shown:
and if I click index in the sensorTag page (pic above) I get to see the data:
the question is , how can I write a simple nodejs js file that uses the mqtt broker information to grab all the sensorTag sensors data and save it in an local object.
I tried to do run this example but no luck
var mqtt = require('mqtt')
client = mqtt.createClient(1883, '192.168.1.109');
client.subscribe(what do I write here);
client.on('message', function(topic, message) { console.log(message); });
I don't know what I'm doing wrong
UPDATE:
mqtt configuration page :
javascript file :
and I run the js with node and listen on port 1883:
tcpdump seems to detect mqqt packets on 1883 port but I can't to seem to be able to console.log the sensor data when I run the js file with node ??
I went on the contiki wiki and came across this info
"You can also subscribe to topics and receive commands, but this will only work if you use "Org ID" != 'quickstart'. Thus, if you provide a different Org ID (do not forget the auth token!), the device will subscribe to:
iot-2/cmd/+/fmt/json"
does this mean that the topic to subscribe to is quickstart but even if that's so, I used '+/#' which subrcibes to all topics and still got nothing printing on the console ?
Hope this works for you:
var mqtt = require('mqtt');
var fs = require('fs');
var options = { port: PORT, host: HOST };/*user, password and others authentication if there.*/
var client = mqtt.connect('HOST', options);
client.on('connect', function ()
{
client.subscribe("topic, command or data");
client.publish("topic, command or data", data, function () {
});
});
client.on('error', function () { });
client.on('offline', function () { });
client.on('message', function (topic, message) {
console.log(message.toString());
});

I have a video js file that I must pause using websockets?

The problem is that I have a C++ Application that must send a message to a tcp server, which then sets a flag .The javascript client must keep on polling this server for the flag status , once the flag has been set. stop playing the video . I am really having trouble Implementing this ?
My websocket dies as I poll the tcp node js server
Video js client code:
function myTimer()
{
var socket = io.connect('http://localhost:7777');
socket.on('connect', function () {
//test(ex1);
alert("test");
});
}
var myVar=setInterval(function(){myTimer()},1000);
Server code node js:
var io = require('socket.io').listen(7777);
var flag = 0;
io.sockets.on('connection', function (socket) {
socket.on('myClick', function (data) {
socket.emit('myClick' , data);
});
});
For everyone who wants a heads up to this question , I was making a mistake of not setting the sockets.io parameters correctly and this other stack overflow answer resolved my doubts
Extra params with socket.io

WebRTC videochat through Websockets

I'm trying to develop a video-chat application using webRTC and WebSockets for signaling.
My problem is that I don't know exactly what is the process of creating RTCPeerConnection and connect both peers(2 browsers) through webSocket(Locally at least).
I know how to communicate clients though WebSockets, but not with the RTCPeerConnection API, you know any tutorial step-by-step explaining the process?(Offer SDP, answers, ICE, ...) and, on the other hand, how looks the server code to managing these clients through RTCPeerConnection?
Here is my Node.js code for the server
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-webrtc';
// Port where we'll run the websocket server
var webSocketsServerPort = 1337;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/* ---------------------------------
GLOBAL VARIABLES
----------------------------------*/
// latest 100 messages
//var history = [ ];
// list of currently connected clients (users)
var clients = [ ];
/* ---------------------------------
HTTP SERVER
----------------------------------*/
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
/* ---------------------------------
WEBSOCKET SERVER
----------------------------------*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
console.log((new Date()) + ' Connection accepted.');
// user sent some message
connection.on('message', function(message) {
for (var i=0; i < clients.length; i++) {
clients[i].sendUTF(message);
}
});
// user disconnected
connection.on('close', function(conn) {
console.log((new Date()) + " Peer " + conn.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
});
});
You might want to have a look at the codelab I did for Google I/O: bitbucket.org/webrtc/codelab.
Step 5 shows how to set up a signaling server using socket.io, and Step 6 puts this together with RTCPeerConnection to make a simple video chat app.
You might also want to have a look at easyRTC (full stack) and Signalmaster (signaling server created for SimpleWebRTC).
The 'canonical' WebRTC video chat example at apprtc.appspot.com uses XHR and the Google App Engine Channel API for signaling.
Have you looked at or come across WebRTC.io? It is an opensource GitHub project that utilizes Node.js and websockets to do the exact thing you are talking about. I, not being much of a javascript person, was able to figure out what it was doing within a week. It isn't a step by step instruction, but anyone with javascript experience would be able to figure out the function call order.
There are two bits to the code: the server side and the client side. The server side is run with Node.js, and serves up the client side code to the browser. If I remember correctly, since the two projects are separate, if you want to combine them you will have to copy the webrtcio.js file from the client side and paste it into the server side folder. Although, I think if you clone the github repository right, you might not have to worry about that.

Node.js WebSocket Broadcast

I'm using the ws library for WebSockets in Node.js and
I'm trying this example from the library examples:
var sys = require("sys"),
ws = require("./ws");
ws.createServer(function (websocket) {
websocket.addListener("connect", function (resource) {
// emitted after handshake
sys.debug("connect: " + resource);
// server closes connection after 10s, will also get "close" event
setTimeout(websocket.end, 10 * 1000);
}).addListener("data", function (data) {
// handle incoming data
sys.debug(data);
// send data to client
websocket.write("Thanks!");
}).addListener("close", function () {
// emitted when server or client closes connection
sys.debug("close");
});
}).listen(8080);
All OK. It works, but running 3 clients, for instance, and sending "Hello!" from one will make the server only reply "Thanks!" to the client which sent the message, not to all.
How can I broadcast "Thanks!" to all connected clients when someone sends "Hello!"?
Thanks!
If you want to send out to all clients, you have to keep track of them. Here is a sample:
var sys = require("sys"),
ws = require("./ws");
// # Keep track of all our clients
var clients = [];
ws.createServer(function (websocket) {
websocket.addListener("connect", function (resource) {
// emitted after handshake
sys.debug("connect: " + resource);
// # Add to our list of clients
clients.push(websocket);
// server closes connection after 10s, will also get "close" event
// setTimeout(websocket.end, 10 * 1000);
}).addListener("data", function (data) {
// handle incoming data
sys.debug(data);
// send data to client
// # Write out to all our clients
for(var i = 0; i < clients.length; i++) {
clients[i].write("Thanks!");
}
}).addListener("close", function () {
// emitted when server or client closes connection
sys.debug("close");
for(var i = 0; i < clients.length; i++) {
// # Remove from our connections list so we don't send
// # to a dead socket
if(clients[i] == websocket) {
clients.splice(i);
break;
}
}
});
}).listen(8080);
I was able to get it to broadcast to all clients, but it's not heavily tested for all cases. The general concept should get you started though.
EDIT: By the way I'm not sure what the 10 second close is for so I've commented it out. It's rather useless if you're trying to broadcast to all clients since they'll just keep getting disconnected.
I would recommend you to use socket.io. It has example web-chat functionality out of the box and also provides abstraction layer from the socket technology on client (WebSockets are supported by Safari, Chrome, Opera and Firefox, but disabled in Firefox and Opera now due to security vulnerabilities in ws-protocol).

Categories

Resources