webdis connection time for second client - javascript

I am using webdis (https://github.com/nicolasff/webdis) I ran the webdis as directed in the website and included the following javascript code to connect:
var previous_response_length = 0
xhr = new XMLHttpRequest()
xhr.open("GET", "http://localhost:7379/SUBSCRIBE/hello", true);
xhr.onreadystatechange = checkData;
xhr.send(null);
function checkData() {
if(xhr.readyState == 3) {
response = xhr.responseText;
chunk = response.slice(previous_response_length);
previous_response_length = response.length;
console.log(chunk);
}
};
When I open up the connection in a web page and opens up two tabs, it takes the secondly opened tab about 10 seconds to start subscribing and listening to messages published. Is there anyway to reduce that wait time for the second client to connect and make it instant? Anything I could add?

Related

Make changes instantly PHP or Javascript [duplicate]

This question already has answers here:
Short-polling vs Long-polling for real time web applications?
(3 answers)
Closed 12 months ago.
I have a chat system but I want both the notifications and the messages to be updated immediately, I am using this code (setInterval) but it makes requests every 500 seconds so I think it is not very efficient, is there another way to do it?
setInterval(() => {
let xhr = new XMLHttpRequest();
xhr.open("POST", "INCLUDES/funciones/get-chat.php", true);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let data = xhr.response;
chatBox.innerHTML = data;
if (!chatBox.classList.contains("active")) {
}
}
}
}
let formData = new FormData(form);
xhr.send(formData);
}, 500);
You should check WebSockets. You can lower the time between requests lowering the second parameter of setInterval but that would be bad. It would be a huge stress for your server that see a spike in the number of requests.
WebSocket, as the name said, open a socket, a permanent comunication channel between the server and client. This allows the server to send messages to the client.
The advantage is that if no message is ready for the client no traffic is sent and no new requests are made from the client to the server.
This is not the right place for a full chat code example because it's quite long. You can see Socket.io not the fastest but maybe the easiest library to work with WebScokets. Here you can find an example of a working chat (server and client) using Socket.IO

JavaScript to reconnect/refresh/stay upon high load or about to timeout

I need some help in here. I have a transition or 2 web page (aspx). The first page was to play video and after finish playing, it will be redirected to page 2 and then back again to page 1. The loop will continues 24/7 in smart TV via web browser.
I am having an issue where I will need to go grab the remote controller to refresh/reopen the web page whenever facing connection lost:
or connection timeout:
I tried to fix this problem by adding some JavaScript to check the connection availability:
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
function myHandler(e) {
if (Offline.state === 'up') {
window.location.href = '../Slide/SlideshowLSI.aspx';
}
else {
this.currentTime = 0;
this.play();
}
}
</script>
What this code does is simply check the connection availability before the redirect to the next page. If it detects that the connection was not available then it will set the video play back to 0 and continue to play the video again. Then it will redirect to the next page after video playback is done and connection is available.
I think this will solve the issue regarding the lost connection problem but not for the connection timeout problem.
I am still facing an issue if a connection timeout occurs and I will need to grab the remote controller to refresh/reopen the web page again on each of the smart TV. I have total of 15 smart TVs currently opening these pages 24/7.
Anyone know how I can solve this problem regarding the connection timeout problem? I tried to search on the internet but all I get is just to check for connection lost problem. I need something that checks the response time before redirecting to the next page, so that I can avoid the connection timeout error page. If the response time were too long, the web page will not be redirected to the next one, but will keep on attempting and redirect to the next page when the response time is not too high that will not cause the connection timeout.
Sorry for my English. Do comment if my explanation was not complete... Thank you.
If you're using JQuery you could simply fire off an AJAX request with a timeout and catch the success/error.
<script>
function ping(){
$.ajax({
url: '/Slide/SlideshowLSI.aspx',
timeout: 3000,
success: function(result){
window.location.href = '../Slide/SlideshowLSI.aspx';
},
error: function(result){
this.currentTime = 0;
this.play();
}
});
}
Otherwise in plain Javascript something like this should work:
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/Slide/SlideshowLSI.aspx');
xhr.timeout = 4000; // Set timeout to 4 seconds
xhr.send(null);
xhr.ontimeout = function () {
console.log("timed out");
}
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK)
console.log(xhr.responseText); // 'This is the returned text.'
} else {
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
}

Multiple javascript Ajax requests seem to work synchronous

This is my first part of code. I here have a list of all the api calls I need to do to retrieve data from the mySQL server.
function ProcessUrls() {
requests = [];
var urls = ['url1', 'url2', 'url3' 'url4'];
for(i=0;i<urls.length;i++)
{
requests.push(new ProcessUrl(urls[i]));
console.log('Invoking the functions');
}
}
The 'Invoking the functions' log in the code above this line of text gets called 4 times almost instantly, as you would expect.
Here I process the urls and do the actual API calls:
function ProcessUrl(url) {
var http = new XMLHttpRequest();
http.open("GET", url, true);
http.send(null);
console.log('Function being called');
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log('Done doing the API call');
}
}
};
}
The "function being called" log gets called almost instantly 4 times as well, the problem is that the 'Done doing the API call' seems to run synchronous since the logs appears slowly one a time in a constant rhythm of ~0.5 seconds.
Is there a way to run these onreadystatechange parallel? This would speed up the process greatly.

How to make XMLHttpRequest reuse a TCP connection?

I have Apache running on Windows 7 Pro. I installed Apache using XAMPP bundle.
I need to call an API once every second. To do that, I created a SharedWorker who calls the API every second using XMLHttpRequest
However, I am running into an issue where the web server Apache hits it's max TCP connection allowed. Of course I can increase the allowed TCP connections on the server, but that does not solve my problem it only patches it until the server gets busy and overloaded.
After troubleshooting the TCP problem, it become clear to me that the XMLHttpRequest is not reusing an existing TCP connection. It opens a new TCP connection with every request/every second. I expect to have 1 TCP connection to be utilized to handle my XMLHttpRequest connection.
While I was the only user is connection to the website on the server, I launched TCPView on the web server to watch the tcp connections. I started out with 30 TCP connection with a state of TIME_WAIT. Every second later, one more connection was created until it reached about 122-130 and then it stopped. Now the server seems to be recycling the connections every 60 seconds, but still generating a new TCP connection for every XMLHttpRequest every second.
I also understand that each time a page is loaded the client/browser could create multiple TCP connection for various of reasons. But, I am expecting to have 1 TCP connection to handle my XMLHttpRequest and resuse that connection over and over.
I know some may suggest using WebSockets or Server-Sent-Events, but in my case I can't. I must keep my ShardWorker implementation.
Question
What can I do to make the XMLHttpRequest reuse of an open TCP connection?
Below is my ShardWorker implementation i.e. worker.js
var clients = new Array();
var xhr = null;
//runs only when a new connection starts
onconnect = function(event) {
var port = event.ports[0];
clients.push(port);
port.start();
//implement a channel for a communication between the connecter and the SharedWorker
port.addEventListener("message",
function(event) {
replyToClientMessage(event, port);
} , false
);
}
//reply to any message sent to the SharedWorker with the same message but add the phrase "SharedWorker Said: " to it
replyToClientMessage = function (event, port) {
port.postMessage("Worker Replied With: " + event.data);
}
//check all open clients and post a message to each
function notifyAllPorts(msg){
var len = clients.length;
var port;
for(i = 0; i < len; i++) {
port = clients[i];
port.postMessage(msg);
}
}
function checkQueue(cb) {
//create a new XMLHttpRequest only once
if (xhr == null) {
xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", cb);
xhr.addEventListener("load", handlerMessageReceived);
}
xhr.open('GET', '/add-ons/icws/push.php', true);
xhr.send();
}
//handler a sucessfull request
function handlerMessageReceived()
{
var queue = JSON.parse(this.responseText);
notifyAllPorts(queue);
}
var promise = Promise.resolve(true);
setInterval(function () {
promise = promise.then(function () {
return new Promise(function (resolve) {
checkQueue(resolve);
});
});
}, 1000);
Here is how I put Sharedworker to work
//establish connection to the shared worker
var worker = new SharedWorker("/add-ons/icws/js/worker.js" );
//listen for a message send from the worker
worker.port.addEventListener("message",
function(event) {
console.log(event.data);
processServerData(event.data);
}
, false
);
worker.onerror = function(event){
console.log(event);
};
//start the connection to the shared worker
worker.port.start();

receive multiple responses in javascript with one request

How can I receive multiple responses from a server using javascript.
I have a requirement where a request is posted one time with the data and number of iterations and at server side the request is processed for the number of iterations. On completion of each iteration the server sends back the response. So for one request and 10 iterations my java script need to receive the 10 responses and show it on the web page. Is there any way that I can handle this using javascript. I cannot use any other technology.
Right now I am using the following way
function showResponse(){
xmlHttp = GetXmlHttpObject();
var dataString = document.getElementById("request-parameters").value;
var iterations = document.getElementById("iterations").value;
if(xmlHttp==null){
alert("your browser does not support AJAX!");
}
var url = "http://localhost:8080/servlet/requestServlet";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(dataString);
}
function GetXmlHttpObject(){
var xmlHttp=null;
try{
//Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}catch(e){
//IE
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function stateChanged(){
if(xmlHttp.readyState==4){
if(xmlHttp.status == 200){
var resp = xmlHttp.responseText;
var responseDiv = document.getElementById("response");
responseDiv.innerHTML=responseDiv.innerHTML+resp1[1];
}
}
}
I cannot modify this approach. Is it possible to get it done with XmlHttp object.
With just 'basic javascript' you cannot do this.
It just works like this: Client sends request, servers returns 'something'. The server cannot simply keep sending data back to this client for multiple reasons. A: There is not a 'link' aka connection between both party's except for the first 'call' of a request, but the client just waits for the response.
B: The script does not expect an other answer back.
What you need is a websocket for example. This way the client can listen to the server and actually process data send from the server to the client.
So in short:
Javascript works always like this:
Client -> Server | and the server respond back
For a socket you can have:
Client -> Server
Server -> Client
You can use some sort of 'javascript' even tho its a different technology.. like NodeJS.
The other way is to make a loop. Rather than posting a dataset with an amount of iterations, just iterate it in JS and for each iteration send it to the server to actually 'perform' on your data.
1) HTTP Try request once to one controller, and then get answer from other controller, you can do this with jQuery or with native XmlHttpRequest (it is not one request).
$.get("server/controllerJob",{data:"data"});
var askInterval = window.setInterval(function(){
$.get("server/askAnswerFromJob",{data:"data"}).done(function( data ) {
if(data.complete){
/** do staff**/
window.clearInterval(askInterval);
}else{
/** do staff**/
}
});
},200);
2) webSocket Or try to find something about WebSocket webSocket documentation, it is techonolgy with one connection with multiple request and response (full-duplex connection stream).
Also you need other server controller realization and see websocket
supported browsers
Notice the ws:. This is the new URL schema for WebSocket connections.
There is also wss: for secure WebSocket connection the same way https:
is used for secure HTTP connections
I'm only just noticing that the "examples" web app that comes with
Tomcat 7 contains 4 complete examples of how to use WebSocket (for java developers)
var connection = new WebSocket('ws://server/yourService',['soap','xmpp']);
connection.onopen = function () {
connection.send('ask'); // Send the message to server
};
//Each time on new messages from server, this callbacks will be executed (depends on result)
// Log errors from server
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
// Get messages from the server
connection.onmessage = function (e) {
console.log('Answer: ' + e.data);
};

Categories

Resources