Chat application like facebook using ajax - ajax

I want to develop a chat application like facebook. I did this and now it works fine. I used ajax for continuing server request to save and retrieve data. One function which is called each 10 second:
// Load message
(function loadClient() {
$.ajax({
type: 'POST',
data: 'c_id=' + $.cookie("c_id") + '&offset=' + $('#c_name_msgHead').data('offset'), //'foo='+ bar+'&calibri='+ nolibri,
dataType: 'json',
url: $("#webroot").text() + 'chats/loadMsg',
success: function (data) {
var id =0;
if ($.cookie("status") == "active"){
$.each(data, function (i, item) {
if(item.Chat.status == 'active'){
$('.temp_msg').remove();
}
if (!$('#' + item.Chat.id)[0]) {
if (item.Chat.admin_message) {
$('<div class="msg_b" id="' + item.Chat.id + '">' + item.Chat.admin_message + '</div>').insertBefore('.client_area .msg_push');
}
if (item.Chat.client_message) {
$('<div class="msg_a" id="' + item.Chat.id + '">' + item.Chat.client_message + '</div>').insertBefore('.client_area .msg_push');
}
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
id = item.Chat.id;
});
$('#c_name_msgHead').data('offset', id);
}
},
complete: function () {
// Schedule the next request when the current one's complete
setTimeout(loadClient, 3000);
}
});
})();
// END load message
It load update data after 10 second. Now if there are 10000 users at a time 10000 request will be send to my server which is a concerned of performance and shutdown of server may occur. Even if 10000 users did not start chatting 10000 request will be performed. So what should I do to develop such application which need to tiger server continuously or which technology is used for facebook chatting. Any idea will be appreciated. Thanks

Facebook is using the technique called Long Polling.
However,for chatroom with high respond rate, it is strongly suggested and much better to use socket.io with node.js as your server side which makes use of sockets to achieve most realtime bi-directional communication channel between a client and a server.
You can read the following tutorial as your starting point
http://socket.io/get-started/chat/

Related

Client side API requests faster than proxy requests via node

Currently I am developing an app that fire off hundreds of concurrent requests to external API service (like instagram for example) using ajax on client side. Response time is very fast.
However, I am migrating the request handling part to node backend using request + jsonstream but always get socket hang up error due to concurrency > 5 requests (even after changing maxsockets to higher values). Overall it is much much slower than doing API requests directly on client side using ajax.
My question is how can I make the proxy server faster/more responsive? Or maybe using ajax similar to when doing on client side but on node?
Server side: when client hits endpoint /fetchmedia/, node directs to this function.
var fetchInstagram = function(user_id, max_id, min_timestamp, max_timestamp, array, callback) {
http.request({
host: 'endpoint',
path: 'endpoint',
method: 'get'
}, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var data = JSON.parse(body);
array = array.concat(data.data);
if (data.pagination.next_max_id != undefined) {
fetchInstagram(user_id, data.pagination.next_max_id, min_timestamp, max_timestamp, array, callback);
} else {
callback(array);
}
});
}).on('error', function(e) {
console.log("Got error: ", e);
}).end();
Client-side: Backbone sends hundreds of requests (/fetchmedia) at the same time, which calls many fetchinstagram functions. The way I was doing before was sending ajax, which also hundreds concurrently but it handles very well. Node hangs up even with 20 users while ajax handles 1000+ users
Thanks

How to use Web worker with AJAX

Is there is any way to call ajax function in web worker.Actually i am directly using ajax function to get the response but data is too much heavy,due to that my window is going to be freeze until the response will come.To overcome this problem now i am using web worker.The data(JSON) is dynamic.So can you please tell me how to call ajax function so that i can use it in my application.Here i am attaching web-worker code.
//Worker.js File
var myCallback = function(data){
self.postMessage(JSON.stringify(data));
};
self.addEventListener('message', function(e) {
importScripts('json.js?callback=myCallback');
}, false);
//JOSN.js File
function getResult(){
var randomNum = (Math.floor(Math.random() * 5) + 1),
cacheBuster = (Math.floor(Math.random() * 10000) + 1);
$.ajax({url:'http://examples.kevinchisholm.com/utils/json/jsonp.php?callback=myCallback&cacheBuster=' + cacheBuster + '&sleep=' + randomNum,
type:'POST',cache:false,data:datas,dataType:"json",async:false,
success:function(xmlResponse){
return xmlResponse;
}});
}
getResult();
Yes you can definitely use ajax in web worker by simply using XML Http Request or fetch API and can post the message using postmessage by using my code hope it helps:->
#Declaring Worker
var worker= new Worker("ajax123.js");
worker.onmessage=function(data){
document.body.innerHTML=data.data;
}
#Web Worker Code
fetch(filename)
.then(response => { return response.text(); })
.then(data => { self.postMessage(data) });

socket.io setinterval way

I want to make a web page for give the client the news of his friends every 1 second using socket.io + node.js.
My codes :
Client :
var socket = io.connect('http://localhost:port');
socket.on('connect', function(){
socket.emit('hello', 'Hello guest');
});
socket.on('news_by_server', function(data){
alert(data);
});
setInterval(function(){
socket.emit('news', 'I want news :D ');
}, 1000);
server:
var io = require('socket.io').listen(port);
io.sockets.on('connection', function (socket) {
socket.on('hello', function(data){
console.log('new client connected');
});
socket.on('news', function(data){
socket.emit('news_by_server', 1);
});
});
that's the mains codes, but my question is about the INTERVAL, is it good the make realtime news or there's a way better then it.
There is no need for the client to ask for news. You can force the server if you want to emit every 1 second - as long as there are clients connected, they will receive updates. If there are no clients connected, you will see in the logs that nothing happens.
On the server
setInterval(function(){
socket.emit('news_by_server', 'Cow goes moo');
}, 1000);
On the client
socket.on('news_by_server', function(data){
alert(data);
});
That's pretty much the standard way to do it. If you've not already looked the example apps page on socket.io, there's a beibertweet example that does just this using setInterval.
Also there's a slightly more advanced example on this blog.
Plus .. I found Ryan Dahls's intro on YouTube really useful for understanding the basics of node operation.
Hope that helps.

ajax settimeout to refresh div

I am displaying a graph using jQplot to monitor data.
To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below).
On the server, a PHP script retrieves the data from a database.
On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000).
On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message.
Monitoring XHR learns that the browser crashes after approximately 200 requests.
As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing.
This works, but is not an ideal situation.
Any better solution to this problem is very much appreciated.
Thanks and regards, JZB
function ajax() {
$.ajax({
cache: false,
url: 'monitor.php',
data : { x: id },
method: 'GET',
dataType: 'json',
success: onDataReceived,
error: onDataError
});
function onDataReceived(series) {
$('#chartdiv_bar').html('');
$.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));
errorcount = 0;
setTimeout(ajax, 5000);
}
function onDataError(jqXHR, textStatus, errorThrown) {
errorcount++;
if (errorcount == 10) {
alert("No server response:\n\n" + textStatus + "\n" + errorThrown);
} else {
setTimeout(ajax, 5000);
}
}
}
Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.
you may want to try to clear the current timer and then start the next timer
var t; //global
In each of your call back functions:
if(t)
clearTimeout(t);
t = setTimeout(ajax, 5000);
more info on timer here: w3 school
I removed the jqplot call as suggested and the problem disappeared.
Apparently jqplot is the culprit and I found numerous entries referring to jqPlot memory leaks.
I use jQuery 1.6.4 and installed jqPlot Charts version 1.0.0b2_r792 which supposedly addresses memory leak issues.
Furthermore, I replaced
$('#chartdiv_bar').html('');
with
$('#chartdiv_bar').empty();
Thank you for your support.

AJax Testing - Add a delay

I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html

Resources