TcpClient don't receive any data with ajax call - javascript

I'm struggling to find out why TcpClient don't receive any data in server side if it has called through ajax.
However, if I put breakpoint in my server side code it works fine even if I have called it with ajax.
I also investigated to find out if my JavaScript function is asynchronous but it seems my JavaScript function is fine.
JavaScript function:
$('#btnGO').click(function () {
var url = 'Home/Command';
var data = { Location: $('#Location').val() };
$.when($.getJSON(url, data)).then(function (result) {
$('.Console').html(result);
});
});
Server side:
TcpClient tc = new TcpClient("Host Address", 23);
return Json(tc.Connected + " " + tc.Available, JsonRequestBehavior.AllowGet);
Output if I put breakpoint in serverside:
true 22
Output if I don't put breakpoint in serverside:
true 0

I think you'd want to call GetStream(), and then call Read() on the returned NetworkStream. Read() is blocking, and won't allow your action method to return prematurely. Right now, there are no blocking calls to prevent your action method from instantly returning (faster than your tcp client receives data), which is why you get 22 when you put in a break point - it doesn't instantly return. It seems awkward that your UI responsiveness depends on somebody sending data to your API via a socket though....
let me emphasize this more: It's really strange what you're doing. Your UI will be waiting for a client to send data to your API via a socket. Having said that, check out the following link: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx

Related

Stop AJAX XHR call but still continue with PHP

Good afternoon,
I have the following functions that shows and hides a page busy loader:
busyStatusDelay = 1000; //milliseconds
var timer = null;
var show = false;
function busyShow(nodelay,delay) {
timer = setTimeout('busyDelayShow()',busyStatusDelay);
}
function busyDelayShow() {
if ($.active > 0) {
$('#json-overlay').css('display', 'table');
show = true;
}
}
function busyHide() {
clearTimeout(timer);
timer = null;
show = false;
$('#json-overlay').css('display', 'none');
}
This works great for normal ajax queries, we however have a new function that should send emails with SMTP, but this SMTP connection takes a few seconds too long to connect and send the emails.
To avoid this I want the ajax function to not trigger this loader, the function does not call the function to open the loader, but the issue is that when another function gets called that should open the loader, it picks up that there is an active connection so the loader comes back up and does not go away.
I tried to use the following so that the JS does not see it as an active request:
xhr.abort(); busyHide();
but when the ajax gets aborted the php aborts with it.
Note that the functions to send the emails should run in the background and should not wait for a response.
I have been searching for a way to disconnect from the server request without affecting the server's functions running and send the email.
I saw ignore_user_abort in another post so will be doing some reading up on this to see if this will work without affecting the rest of the system.
Thanks in advance for any tips on how to continue!
A good approach to this would be to execute your SMTP as a background process using some sort of queuing mechanism. So basically, whenever a JS triggers AJAX to mail, the PHP push the email request to a queue and send a response back to the XHR immediately. This way, your AJAX execution won't be blocked for long.
If you are using some sort of PHP framework like Laravel, it makes easier to manage queues otherwise have a look at this post.

sending continuous text data from java code to html via http request

I am working on developing an application where i am am doing http post request via angular and then this request is received by Java code, code does its stuff and generate logs of about 50-60 lines creating one line every seconds.
I want to show these logs on my html page as they generate, right now i am collecting all logs and displaying them once the request finishes?
Can this be done in continuous manner?
JAVA CODE
Java code create array of logs of size 50-60, it takes 60-90 seconds to finish the operation, and i am sending array with below code after converting it to JSON
response.getWriter.write(applogs)
JAVASCRIPT CODE
var httpPostData = function (postparameters,postData){
return $http ({
method : 'POST',
url : URL,
params : postparameters,
headers: headers,
data : postData
}).success (function (responseData){
return responseData.data;
})
}
var addAppPromise = httpPostData (restartAppParams,app);
addAppPromise.then(function (logs){
$scope.logs = logs.data;
})
HTML Code
<span ng-repeat="log in logs">{{log}}<br></span>
You have at least two options:
(Uglier but faster and easier one) Make your service respond immediately (don't wait for 'stuff' to be generated) and create second service
that would return logs created so far. Then in JS implement polling: call this second service in short, fixed intervals and update view.
Use EventSource to get server sent events .
You can also use websockets, but since you only want your server to
feed client, EventSource should be enough. However, keep in mind that this API will require polyfills for IE/Edge and special handling on the server side.

Waiting till call back completes Node.js

My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
var http = require('http');
var server = http.createServer(req,resp) {
var finalVal = "";
consumer.on('message',function(message) {
finalVal = message;
console.log(finalVal);
});
resp.end(finalVal);
});
My finalVal should display all the multiple values it fetches and send it as a response, but problem is it's sending only first value where as console.log displays all the values. I do understand that by the time consumer.on ends response would have committed. Can someone please help me how to handle this scenario since I'm very new to Node.js ? Currently due to heavy deadlines I don't have time to read full information about callbacks. But defnitely I would take time to learn about callbacks.
Edit: Here consumer.on calls multiple times till it fetches all the data from backend, I need to send all those data in a final response. I am using node-kafka to consume to kafka messages.
There must be an end event or something like that which tells that consumer has finished the message, you can use that
I am not sure what is consumer here, but in most of cases we go with something like bellow
var finalVal = '';
consumer.on('message',function(message) {
finalVal += message; // So on each message you will just update the final value
console.log(finalVal);
});
consumer.on('end',function(){ // And at the end send the response
resp.end(finalVal);
});

custom events with server sent events

I am trying to utilize server sent events to handle the client side of some async operations im doing server side. Scroll to the bottom to see the final question.
What I have is an web app that needs a global search. The returns can be massive and take some time as they are actually sent to a webservice and then returned as XML.
I am trying to use server sent events (javascript: EventSource) to enable this. It works great for just one event but if I want to do a bunch of different events it gets a little weird, at least for me. I am new to SSE.
so far I have done this:
var sse = new EventSource('testsse.aspx');
function init() {
sse.onopen = function (e) {
console.log(e.data);
};
sse.onmessage = function (e) {
//if data has been returned the "data:" field will not be empty so we know the server operation is complete.
if (e.data.length>0) {
$('#rgCcr').kendoGrid({
dataSource: JSON.parse(e.data)
});
sse.close();
}
console.log("message: " + e.data);
};
$(document).ready(function() {
init();
});
on the server I have an aspx page that is building the json strings. as I mentioned I have it working great if I just use the standard "data: my message\n\n" format. What I need to do is get a few more pieces of info in there.
The spec for SSE says that you can specify an event to fire. I cant get this to work so far though.
in my aspx I am building the string like this:
json = string.Format("id:{0}\n event:myEvent\n data:{1}\n\n", id, ser.Serialize(ccrData));
I have tried creating a custom event but I am not sure what to bind it to in order to catch it.
On the page I have 5 different areas that are being search as part of the global search. Each is executed as an async task on the server and as they complete they will send the data back to the client. once the client detects the event has submitted data it will close the listener and add the data results to the kendo grid.
How can I use the event field of the SSE to tell the difference between what is coming back?
Rather than using the "onmessage" function, you could try registering an event listener. That way you can choose to listen to a particular event type.
es = new EventSource('/events', withCredentials: true);
es.addEventListener("open", function (e) {
alert("Connecting...");
});
es.addEventListener("error", function (e) {
alert("Error");
});
es.addEventListener("myEvent", function (e) {
alert("MyEvent");
alert(e.data);
});
There's great documentation here:
http://html5doctor.com/server-sent-events/

Javascript Error when updating client using AJAX call

I am trying to model a chat application on a browser(Firefox).Here I am trying to send the char inserted into a text area on one machine to another client and update its text area.
I am trying to send the key pressed on the client using AJAX calls. Below is the function call that I have written :
function returnKeyFromCode(code)
{
//Returns char code
};
function keyPress(e)
{
var textReplace = document.getElementById("textReplace");
var keyPressed = returnKeyFromCode(e.which) ;
textReplace.innerHTML = keyPressed;
var locationReplace = document.getElementById("location");
locationReplace.innerHTML = mainDoc.selectionStart;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){};
xmlhttp.open("POST","http://localhost:5000?key=" + keyPressed + "&pos=" +mainDoc.selectionStart +"&revno=1&param=EOS",true);
xmlhttp.send("Stuff");
};
At the client side, when the char is received the following error is displayed on the fire bug console:
'0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]' .
Before sending the data, a persistent connection is being set up between client ans server using another Ajax call.
It looks like you've edited some of your code before posting this question, so I can only speculate, but based on the error, i'd guess at some point you're sending null to this function: xmlhttp.send("Stuff");
Try doing a null check on the data before you send it, or possibly make sure whatever starts the send process is in a document ready, so that you're not trying to grab data from an undefined text element.

Categories