Problems with online visitor tracking - websocket

I am working with web-socket project. We are tracking the customers of the website and showing that information to our customers dashbaord.
For this we are using pubnub service. They have api to subscribe and her_now to get currenly active connections. But seems it is not working properly. It is not tracking as we expecting.
It is not sending events properly when customers have lot of traffic(>150 active). And even his cost is too high.
We are planning to move to some other technique to do this. Please suggest which one is the good option.
How about nodejs with socket.io. One thing i am thinking the scalability when our customers have lot of traffic.
Please suggest on this.
Thanks,
Govind.

Move to Socket.io (It,s support mobile and all browser) and performance is good
Problems with online visitor tracking:
Here is my answer,When user visit you website you emit some event using following code
Server side:
var io = require('socket.io');
io.sockets.on('connection', function (socket) {
//From user
socket.on('userEnterYourWebsite',function(data){
//Do some DB operation means retrive user related information from DB
//If emit some data to user
socket.emit('sendToUser',{name:'mmm',state:'tamilnadu'});
});
});
Client Side:
<script>
var socket=io.connect('http://ipaddress:8080');
var userIDorUniqueID='mmmmmmm';
socket.emit('userEnterYourWebsite',{uniqueID:userIDorUniqueID});
//From server
socket.on('sendToUser',function(data){
console.log(data.state);
});
</script>

Property Annouce Max
You just need to set the Presence Announce Max property on the Presence add-on higher. Contact support#pubnub.com to set it higher than 100.
Build vs. Buy
What will be the cost of scaling your DIY node/socket.io solution? See the following before considering the DIY route.
http://www.pubnub.com/blog/build-vs-buy-why-diy-isnt-always-better/
http://www.pubnub.com/customers/swaplingo/
http://www.pubnub.com/customers/tint/

Related

Laravel Notification System

I use a simple Query Code to display Toastr in my application. This is the code:
<script>
document.getElementById("test").onclick = function() {
$.toaster({
priority : 'success',
title : 'yassine Jennane',
message : 'yassine jennane test toster'
});
};
</script>
My problem is when there is another user connected in my application, he isn't receiving the notification at the same moment as the first one do. Why?
Link of the notification script + demo: jQuery & Bootstrap Based Toast Notification Plugin
This won't work like that. You need to create Event Classes and Broadcasting Channels. Further you need to have some socket.io node.js side so that the notifications are shown live on the client side.
You probably don't have experience in this subject, so I would suggest to do following things:
Have a look at following in the documentation: https://laravel.com/docs/5.7/broadcasting
Watch following tutorial on laracasts: https://laracasts.com/series/real-time-laravel-with-socket-io/episodes/1
Of course you can have a look at some other tutorials you find on the internet.
The plugin you're using is a Jquery plugin that makes toasts in user browser, it works only for connected user, if you want to show notification for all the users using your application, you should use Cloud Messaging service, Firebase is good one.

Should I use HTTP or xmlhttprequest on node.js? When?

I'm still exploring REST, node.js and generally web development. What I found out is that xmlhttprequest is mostly(if not always) used when using AJAX. As I learned AJAX is for asynchronous Javascript and XML. So my question is should I be using xmlhttprequest in my node.js project, just when I want to do asynchronous parts on my webpage? or does node.js HTTP also have opportunity to asynchronous javascript? How can I balance well the use of HTTP and xmlhttprequest(or AJAX) so that I don't get too messy in all my REST API stuff?
P.S. I kinda don't want to use AJAX, because of XML. I have heard that XML is much heavier in data than JSON and isn't worth using anymore. Is it true? What would you recommend me to do?
non async on node?
you're trying to build an endpoint api so all the other cases of not using async should be thrown out the window. As soon as you have a single non async code in your node.js project it will freeze the entire process until it is complete. Remember Node.js runs a single Thread (theoretically) which means all the other concurrent users are gonna get frozen.. that's one way to make people really upset.
say for instance you need to read a file from your Node.js server on a get request from a client (let's say a browser) well you want to make it a callback/promise never do non-async with an API server there is just no reason not to (in your case).
example below
import * as express from "express";
import * as fs from 'fs';
let app = express();
app.get('/getFileInfo', function(req, res) {
fs.readFile('filePath', 'UTF-8', function(err, data) {
if (err) {
console.log(err);
res.json({error: err});
} else {
res.json({data: data});
}
})
});
//users will freeze while the file is read until it is done reading
app.get('/nonasync', function(req, res) {
let data = fs.readFileSync('path', 'utf-8');
res.json({data:data});
});
the exact same idea applies to your web browser.. if you are going to not do something async in the browsers javascript the entire web application will be unresponsive because it also runs in the same manner, it has one main loop and unless they are in callbacks/promises/observable the website will freeze. Ajax is a much neater/nicer way to implement post/get/put/delete/get:id from a server then an XMLHttpRequest. now both of these have an option to send and receive JSON not only XML. Ajax is safer due to supporting different browser compatibility specs as XMLHttpRequest has some limitations in IE and Safari I believe.
NOTE: if you're not using a framework with node.js you should, it helps keep your endpoints neat and testable along with being able to pass the project on to others without them having to learn the way you implemented your req, res structure
some frameworks for node
Express 4 (my preference, api doc is really really good and strong
community)
Restify (used by Netflix - really light)
Hapi (never used but heard of)
some frameworks for web browsers you might like
angular 2 (my preference as I'm from a MEAN stack)
reactJS (created by big blue Facebook)
knockoutJS (simple and easy)
all the browser frameworks have their own implementation of the RESTful api's, but more are leaning towards Observable objects.

How to disconnect all sockets serve side using socket.io?

How can I disconnect/close all sockets on server side ?
Maybe restarting the socket.io module from the server side ?
(using the lateste socket.io)
Unfortunately, socket.io does not have a publicly documented interface that has been the same from one version to the next to do such a basic function as iterate all connected sockets. If you want to follow the entire history of various ways to do this, then you can follow the whole version history in this question: Socket.IO - how do I get a list of connected sockets/clients?, but you have to pay attention only to answers that apply to specific socket.io versions you are using and then test them for your specific version.
As of Aug 2018, attempting to use only documented interfaces in socket.io, one could use either of these to get a list of connected sockets and then just iterate over them to disconnect them as shown above:
function getConnectedSockets() {
return Object.values(io.of("/").connected);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
Depending upon the client configuration, the clients may try to reconnect.
You could also just maintain your own connect socket list:
const connectedSockets = new Set();
io.on('connection', s => {
connectedSockets.add(s);
s.on('disconnect', () => {
connectedSockets.delete(s);
});
});
function getConnectedSockets() {
return Array.from(connectedSockets);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
If you are using an older version of socket.io (particularly before v1.4), you will have to either test this to make sure it works in your older version or follow the version history in the above mentioned reference and find an answer there that targets your specific version of socket.io.
For me, jfriend00's solution didn't work (as of today).
I had to do this:
Object.keys(io.sockets.sockets).forEach(function(s) {
io.sockets.sockets[s].disconnect(true);
});

Titanium chat implementation

I have an task to implement an chat based application to access private data available at server using web service api call.Show all available users from web server and to chat with those persons.Is't possible with titanium development to support on iPhone/Android chat application. If possible let me guide to implement the same.
Yes, of course it's possible. And there are a million ways to do this, your question is not very clear.
If its totally web services based then just use this.
Heres a quick example of posting to a webservice and sending a JSON object:
var getChatMessages = Ti.Network.createHTTPClient({
onload : function(e) {
var doSomethignWithThis = this.responseText;
},
onerror : function(e) {
Ti.API.info(this.responseText);
Ti.API.info('SelectActivityStepsByKeyList webservice failed with message : ' + e.error);
}
});
getChatMessages.open('POST', 'http://yourchatserver/GetChats');
getChatMessages.setRequestHeader("Content-Type", "application/json");
getChatMessages.send({"message" : "How is everyone today?", "user" : "me#me.com});
This is not difficult with titanium, the hard part is on the server side.
Here is an example project that accomplishes chat through the use of the socket.io library. This may be a better approach for you. The link has a video of how it works as well as the full source code.

About Geolocation in HTML 5

Google Maps can now pinpoint my location with street precision with the help of Firefox.
I understand this is a new feature of HTML 5 compatible browsers and that the location is fetched by using some sort of feature of the connected WiFi network (I hope I'm not making any silly assumptions).
What I intend to know is how this whole process exactly works:
Why only in HTML 5?
Why / how does Firefox ask me to share my location with Google Maps?
What is the normal precision one can count on?
How can I implement this feature in my websites?
Thanks in advance!
How does it work?
When you visit a location-aware website in Firefox, the browser will ask you if you want to share your location.
If you consent, Firefox gathers information about nearby wireless access points and your computer’s IP address, and will get an estimate of your location by sending this information to Google Location Services (the default geolocation service in Firefox). That location estimate is then shared with the requesting website. (Source)
How accurate are the locations?
Accuracy varies greatly from location to location. In some places, the geolocation service providers may be able to provide a location to within a few meters. However, in other areas it might be much more than that. All locations are to be considered estimates as there is no guarantee on the accuracy of the locations provided. (Source)
In my case, Firefox reports that I am about 10km away from my real location.
How do I use this feature in my website?
You would do something like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
alert(position.coords.latitude + ", " + position.coords.longitude);
// Use the latitude and location as you wish. You may set a marker
// on Google Maps, for example.
});
}
else {
alert("Geolocation services are not supported by your browser.");
}
You can see an online demo here: Firefox HTML 5 Geolocation Demo (Requires a geolocation-aware browser such as Firefox 3.1b3.)
HTML5 supplies an API which allows the web browser (and then hence the server-side of an web application) to query the location and related information such as speed (if relevant), in a standard, uniform, fashion.
The host and its web browser supply the "devices" which compute/estimate the geolocation per-se
For this API to be useful, requires that the underlying host and web browser
a) allow the sharing of such info (note the privacy issue) and
b) be somewhat equipped (either locally or by way of the network they are hooked-up to) to read or estimate the geolocation.
The techniques and devices involved in computing the actual location involves a combination of the following (not all apply of course), and is independent from the HTML 5 standard:
GPS device (lots of phones now have them)
Routing info at the level of the Cell phone network
IP address / ISP routing information
Wifi router info
Fixed data, manually input (for pcs which are at a fixed location)
...
Therefore...
- HTML5 alone cannot figure out geolocation: upgrading to newer web browser, in of itself, won't be sufficient to get geolocation features in your applications etc.
- Geolocation data can be shared outside of the HTML5 API, allowing GPS-ready or GeoLocation-ready phones expose the geolocation data within other APIs.
HTML5 Geolocation API uses certain features, such as Global Positioning System (GPS), Internet Protocol (IP) address of a device, nearest mobile phone towers, and input from a user, in the users’ device to retrieve the users’ location. The users’ location retrieved by using the Geolocation API is almost accurate depending upon the type of source used to retrieve the location.
There is a really good demo of HTML5 Geolocation here (http://html5demos.com/geo). Whenever a website tries to fetch your location by using one of the following mentioned APIs, the browser will ask me your permission before invoking the API to share your location.
The Geolocation API provides the following methods:
getCurrentPosition(successCallback, errorCallback, options)
Used to retrieve the current geographical location of a user.
watchPosition(successCallback, errorCallback, options)
The function returns a watchId and calls successCallback with the updated coordinates. It continues to return updated position as the user moves (like the GPS in a car).
clearWatch(watchId)
Stops the watchPosition() method based on the watchId provided.
Sample Code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPositionSuccess, userPositionError);
} else {
alert("Your browser does not support geolocation.");
}
function userPositionSuccess(position) {
alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
}
function userPositionError() {
alert("There was an error retrieving your location!");
}

Resources