Socket.IO transmitting a array per emit(...) - javascript

I am trying to build a array in my socket io server and sending it to the client.
var roomList = io.sockets.manager.rooms;
// new Array to save the clients per room
var clientsPerRoom = new Array();
//for (var i = 0; i < roomList.length; i++) {
for (var room in roomList) {
room = room.replace("/", "");
// get the clients per room
var clients = io.sockets.clients(room).length;
// saving it in the array at the name of the room
clientsPerRoom[room] = clients;
}
// transmit it to the client
io.sockets.emit('roomList', roomList, clientsPerRoom);
On the client side
var clients = 1;
for (room in roomList) {
if (room.length > 0) {
room = room.replace("/", "");
clients = clientsPerRoom[room];
console.log("ROOM: '" + room + "' has '" + clients + "' CLIENTS");
}
}
At the client, "clientsPerRoom" is "[]" (empty?), and so "clients" is "undeined".
What am I doing wrong?
At the console log from the server are the values 1 if a user is connectet. If more users are online then its still 1 but at least it should send this value to the client.
Thanks

Finaly I solved it:
var clients = io.sockets.clients(room).length;
// has to look like this:
//clientsPerRoom = {"test" : 3, "xyz" : 4};
clientString = '"' + room + '" : "' + clients + '",' + clientString;
console.log("clientsPerRoom[" + room + "] : " + clientsPerRoom[room]);
console.log("__END OF LOOP__");
}
}
//cut the "," et the end of the string (else: ERROR!)
clientString = clientString.substr(0, clientString.length-1);
// parse it with JSON to pretend beeing a object
clientsPerRoom = JSON.parse('{' + clientString + '}');
// now send it to the client
io.sockets.emit('roomList', roomList, clientsPerRoom, totalClients);
Now another problem is, that
var clients = io.sockets.clients(room).length;
is always 1...

Even solved yet.
Problem was: io.sockets.clients(room) only counts users who accepted webcam access, otherwise the are not "really" in the room yet.
Greetings

Related

need explanation about node.js npm(express)?

please explain for me how this line work
app.get("/speak/:animal", function(req, res) {
var sounds = {
pig: "OINK",
cow: "MOO",
dog: "WOOF WOOF",
cat: "I hate humans",
goldfish: "..."
};
var animal = req.params.animal.toLowerCase();
var sound = sounds[animal];
res.send("The " + animal + " says '" + sound + "'");
});
and this line too please
app.get("/repeat/:message/:times", function(req, res) {
var message = req.params.message;
var times = Number(req.params.times);
var result = "";
for(var i = 0; i < times; i++) {
result += message + " ";
}
res.send(result);
});
The first one:
// Listens to all the get requests on the url path /speak/anything
// :animal is a placeholder, anything you pass in the url will be be available in the url param animal.
app.get("/speak/:animal", function(req, res){
// JSON object with a key value pair.
var sounds = {
pig: "OINK",
cow: "MOO",
dog: "WOOF WOOF",
cat: "I hate humans",
goldfish: "..."
};
// Converts the request parameter 'anything' in the url to a lower case string.
var animal = req.params.animal.toLowerCase();
// Tries to find the sound in the sounds object since 'anything' is no key it wont find a suitable value for the sound.
var sound = sounds[animal];
// Responds to the request with the resolved sound.
res.send("The " + animal + " says '" + sound + "'");
The second one
// Let us consider that the request /repeat/received/10
app.get("/repeat/:message/:times", function(req, res){
// the /received in the url will be available to access under the req.param.messages
var message = req.params.message;
// message = received
// Converting the times string 10 passed in the url to a number
var times = Number(req.params.times);
var result = "";
// loop will run from 0 to 9 and keep appending to the string result
for(var i = 0; i < times; i++){
result += message + " ";
}
// At the end of the for loop
// result will contain = 'received received received' 7 more time ...
// will send the response to the request.
res.send(result);
});

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Sending multiple HTTP GET requests to api with a loop

I'm looking for a way to send many requests to an api using a different api url each time.
An example url for my project is:
http://api.bandsintown.com/artists/Hippo%20Campus/events.json?lapi_version=2.0&app_id=music_matcher
I'm using an HTTP request to pull the JSON info into my script and works perfectly...the first time. However, I want to be able to call it 50-100 ish times (max) in a loop with different artist names in the url (I'm using the BandsInTown API). For some reason, when I try to use a loop to call the http request multiple times, only one output appears and it is unpredictable which element in the order it will be (it's usually the output associated with the first or second element in the array). This is what my code looks like:
// HTTP GET call to BandsInTown API
function httpGetAsync(theUrl, callback) { //theURL or a path to file
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) {
callback(data);
}
}
else {
alert("error loading JSON doc");
}
};
httpRequest.open('GET', theUrl, true);
httpRequest.send(null);
}
//extracts data from api for each artist
function parseEvent(artist) {
var url = "http://api.bandsintown.com/artists/" + artist + "/events.json?lapi_version=2.0&app_id=music_matcher";
httpGetAsync(url, function(data) {
var numEvents = Object.keys(data).length;
//var events = [];
for (var j = 0; j < numEvents; j++) {
document.write(data[j].venue.name + "-> ");
document.write("LAT:" + data[j].venue.latitude + " " + "LNG:" + data[j].venue.longitude);
document.write("ARTIST: " + data[j].artists[0].name);
document.write("DATE: " + data[j].datetime);
document.write(" " + j + " ");
}
});
}
var artists = ["Drake", "Mac Demarco", "Hippo Campus", "STRFKR"];
for (var i = 0; i < artists.length; i++) {
parseEvent(artists[i]);
document.write(" ---NEXT ARTIST--- ");
}
So I can't tell exactly what's going on but things are acting weird with my current code. I don't have a whole lot of javascript and web development experience yet so any help is appreciated! I was preferably looking for a way to implement this with pure javascript. I have had trouble figureing out how to handle Node.js and/or JQuery in Eclipse Neon (the IDE I am using)
You have implemented closure pretty well so clearly this isn't a problem of success callback of one function overwriting response of all others.But now when you look at document.write() it all gets clear, this function first wipes your whole content clean then it writes whatever you told it to .That's why you hardly see anyone use it
`document.write('a');`
`document.write('b');`
`document.write('c');` // a and b are gone you would see only 'c'
So after loop gets over you would only see the output of the last call.Though it's mostly random as to which call would finish last it mostly biased towards some particular value due to the the way servers are tuned.
So better approach is to use some <div> or something and pour your results into it like this one
<div id="op"></div>
and
function parseEvent(artist) {
var url = "http://api.bandsintown.com/artists/" + artist + "/events.json?lapi_version=2.0&app_id=music_matcher";
httpGetAsync(url, function(data) {
var numEvents = Object.keys(data).length;
var op = document.getElementById('op');
op.innerHTML = op.innerHTML + " <br><br> <h2>---NEXT ARTIST---<h2> <br>";
//var events = [];
for (var j = 0; j < numEvents; j++) {
op.innerHTML = op.innerHTML + "<br>" + data[j].venue.name + "-> ";
op.innerHTML = op.innerHTML + "<br>" + "LAT:" + data[j].venue.latitude + " " + "LNG:" + data[j].venue.longitude ;
op.innerHTML = op.innerHTML + "<br>" +"ARTIST: " + data[j].artists[0].name;
op.innerHTML = op.innerHTML + "<br>" +"DATE: " + data[j].datetime;
op.innerHTML = op.innerHTML + "<br>" + " " + j + " <br>";
}
});
}
var artists = ["Drake", "Hippo Campus", "STRFKR","Mac Demarco"];
for (var i = 0; i < artists.length; i++) {
parseEvent(artists[i]);
}

How can I connect mosquitto server between raspberry pi and windows7?

Hello I'm trying to use mosquitto server in Raspberry Pi using MQTT to send a json data from r-pi to window.
Before I use mosquitto server, I used "test.mosquitto.org" It worked well.
I mean It sended some json data to windows.
However, when I turned mosquitto server in r-pi on, the windows put some error message which is
opts.protocol = opts.protocol.replace, cannot read property 'replace' of null.
Would you mind telling me what it is going on and fix it?
this is javascript on windows code (I use python in raspberry pi)
console.log("start");
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
var client = mqtt.connect('192.168.1.2'); // IP of main-broker
client.on('connect', function () {
client.subscribe('sensor_A');
});
client.on('message', function (topic, message) {
console.log("Topic: " + topic);
var parsedData = JSON.parse(message);
var dataLen = parsedData.length
console.log('dataLen: ' + dataLen);
for (var i = 0; i < dataLen; i++) {
var data = JSON.parse(parsedData[i]);
console.log('data ' + i + ': ' + data.time + ' ' + data.tem + ' ' + data.hum + ' ' + data.gas);
}
});
I am using two r-pi which is sub-borker and main-broker.
sub-broker just send some sensor data as json and main-broker controls the json data and send again as json to windows.
I think my writing is quite complex to understand.
In short, I don't want to use "test.mosquitto.org" in r-pi so I turn mosquitto server on in r-pi to send data to window, however, there a error in window.
First you need to remove the line connecting to test.mosquitto.org as that will just confuse things.
Secondly you have missed out the mqtt:// from the URL for the local instance of mosquitto. The error is points out it can not find the protocol from the url.
console.log("start");
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.1.2'); // IP of main-broker
client.on('connect', function () {
client.subscribe('sensor_A');
});
client.on('message', function (topic, message) {
console.log("Topic: " + topic);
var parsedData = JSON.parse(message);
var dataLen = parsedData.length
console.log('dataLen: ' + dataLen);
for (var i = 0; i < dataLen; i++) {
var data = JSON.parse(parsedData[i]);
console.log('data ' + i + ': ' + data.time + ' ' + data.tem + ' ' + data.hum + ' ' + data.gas);
}
});

Count HTTP only cookies with Mozilla add-on

I'm trying develop a Firefox add-on. I would like to count the cookies that are marked as HTTP only. When manually checking, I have seen that many websites have more than one HTTP only cookie. But, my result is always 0 or 1. Where is my fault?
Here is my code:
var {Cc, Ci, Cu} = require("chrome");
Cu.import("resource://gre/modules/Services.jsm");
var cookieManager = Cc["#mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager2);
var tabs = require("sdk/tabs");
tabs.on('load', function(tab) {
var URL = tab.url;
var url = require("sdk/url").URL(URL);
var host = url.host;
function getCookies(host){
var cookies = cookieManager.getCookiesFromHost(host);
var count = 0;
while (cookies.hasMoreElements()){
var cookie = cookies.getNext().QueryInterface(Ci.nsICookie2);
//var count = 0;
var httpCookie = cookie.isHttpOnly;
if(httpCookie){
return count=count+1 ;
}else{
return 0;
}
console.log("Cookie host: " + cookie.host + "; Cookie Name :" + cookie.name
+ " = Cookie value:" + cookie.value + "\n");
dump("\tCookie host: " + cookie.host + " Is Domain cookie: " +cookie.isDomain
+ "; Cookie Name :" + cookie.name +" = Cookie value:" + cookie.value
+ "; Is Session Cookie :" + cookie.isSession
+ "; Expiry time :" + cookie.expiry
+ "; It is an Http only cookie :" + cookie.isHttpOnly + "\n");
}
return count;
}
var getResult = getCookies(host);
console.log("Http Cookies: " + getResult);
});
Within your function getCookies(host) you have a while loop that is intended to loop through all cookies for the specified host. However, the inner portion of that loop is only executed once.
Within that loop you have an if statement:
var httpCookie = cookie.isHttpOnly;
if(httpCookie){
return count=count+1 ;
}else{
return 0;
}
This statement results in the function immediately returning either a 1 or a 0 depending on if the first cookie found has the property cookie.isHttpOnly as true or false. [Note: cookie is always 0 when this if statement is executed for the first and only time.] No other cookies are checked other than the first one because you immediately return the value. Execution of your function ends at either of the two return statements within this if statement. The lines within the function after the if will not be executed.
From what you describe you desire, your if statement would be better as:
if(cookie.isHttpOnly){
count++;
}
Note: Given that you only use cookie.isHttpOnly once, there is no need to assign it to a separate variable.

Categories

Resources