Read complete data from stream from onMessage - javascript

How to read event.data completely from a WebSocket using JavaScript?
onMessage: function(event) {
var msg = event.data;
alert(msg);
}
In the above code, the variable msg shows only the partial data. How to receive the complete data from the WebSocket server?

event.data contains the full information; it just depends on your output how much you'll see. An alert box can only contain up to a specific amount of characters, because more characters simply wouldn't fit in the alert box. alerting is not a good practice for displaying large data.
A more convenient way is to save the length and check that, e.g.:
onMessage: function(event) {
var msg = event.data;
alert(msg.length);
}
The length should just be the correct length, i.e. the length of the characters you sent.

WebSockets is a message based transport. If the server has broken the "stream" into several message chunks then you will receive several message events and the first message event won't have all the data that you are expecting.
Also, the WebSocket definition requires that the onmessage handler is called for full messages. You can't get partial messages (unless the browser's WebSocket implementation is broken).
I would try something asynchronous instead of alert() to log the messages you receive. For example, try console.log() if you have Firebug or the Chrome Javascript console. Are you accumulating your message data in the HTML text box or just overwriting it as you receive messages?

Related

How to clean alert message from pusher?

I am using PUSHER into my site for notification.
I successfully added the codes and its working.
But the problem is when the alert is getting triggered I am receiving messages but its not what I am looking for.
I am receiving this message from Javascript alert();
{"message":"A new appointment arrived"}
alert message from pusher
And my code is
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
document.getElementById('audio').play();
alert(JSON.stringify(data));
$.ajax({url: "notification", success: function(result){
$("#notification").html(result);
}})
});
And this is where I am getting this.
$data['message'] = 'A new appointment arrived';
$pusher->trigger('my-channel', 'my-event', $data);
I am getting the message from
JSON.stringify(data)
My question is, is there a way I can remove everything except A new appointment arrived from the alert message?
Thanks in advance.
I am a beginner and I have very little knowledge about Javascript.
If I'm understanding your question correctly, what you're asking is how you change the output that gets shown in the alert from
{"message":"A new appointment arrived"}
to just A new appointment arrived. Is that right?
What JSON.stringify() does is convert a JavaScript object into a string of text in the JSON format. Since you're not actually interested in the object, just the message it contains, there really isn't any need to use JSON.stringify here. Assuming that the data you're receiving always has the format
{ message: "Some type of message" }
you can just write alert(data.message) (or alert(data["message"]) if you don't like JavaScript dot notation).
Remove the line: alert(JSON.stringify(data)); in your JS code. That's triggering the alert with the message received from your Event.
You can read more about alert() method here: https://developer.mozilla.org/en-US/docs/Web/API/Window/alert

Simple online web game crash eventually

Background:
I am making a simple game in PHP, JavaScript and HTML for the web. A player control movements of a box on the screen, and see others fly around with their boxes.
I have the following files, that I upload to my domain via a hosting company:
index.html: a file with some buttons (eg. to start the game) and frames (for putting boxes in).
server.php: PHP script that receives messages from client, performs reads/writes to a database, echoes (using echo) boxes from database to the client. Does not echo the box of the player the message came from.
database.txt: a JSON text file containing data of players and the next free ID number. When empty it looks like this: {"players":[], "id": 1}. players contain objects with values such as ID, position and rotation.
script.js: JavaScript file with script to send/receive messages, display data from messages etc. Linked to index.html. Moves your box.
A screenshot, two players in movement:
Problem: The game crashes, always. Sooner or later. This is what happens:
Client recevies player data from server.php, everything is fine. This could be for 10 seconds or up to some minutes.
The data starts to falter, the message sometimes is null instead of actual data.
The data recevied is always null. The database file is now {"players":null,"id":5}. (The "id" could be any number, does not have to be 5).
Picture of data flow, printing of players from database. Two players. Before this screenshot lots of rows with valid data. Then as seen two null messages. Then after a while null forever.
I am not completely sure where the problem is, but I am guessing it has to do with my read/write in server.php. I feels like a lot of player movement makes the program more likely to crash. Also how often the program sends data affetcs.
Code Piece 1: This is code from server.php, that writes to the database. I have some sort of semaphore (the flock( ... ) ) to prevent clients from reading/writing at the same time (causing errors). I have an other function, read, which is very similar to this. Possible problems here:
The semaphore is incorrect.
The mode for fopen() is incorrect. See PHP docs. The mode w is for write. The tag b is for "If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data ...".
Something weird happening because I use read() in my writing function?
Code:
// Write $val to $obj in database JSON
function write($obj,$val){
$content = read();
$json = json_decode($content);
$json->{$obj} = $val; // eg. $json->{'id'} = 5;
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
if(flock($myfile, LOCK_EX|LOCK_NB)) {
fwrite($myfile,json_encode($json));
flock($myfile, LOCK_UN);
}
fclose($myfile);
}
Code Piece 2: This is my code to send data. It is called via a setInterval(). In script.js:
// Send message to server.php, call callback with answer
function communicate(messageFunc,callback){
var message = messageFunc();
if (window.XMLHttpRequest) {
var xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange= function() {
if (this.readyState==4 && this.status==200) {
callback(this.responseText);
}
}
xmlhttp.open("GET","server.php?msg="+message,true);
xmlhttp.send();
}
This is my code to receive data, in server.php: $receive = $_GET["msg"].
My current work of solving
This is what I have done so far, but nothing has changed:
Added mode b to fopen().
Added flock() to read/write functions in server.php.
Much reworking on script.js, I would say it looks/works very clean.
Check memory_get_peak_usage(), and check with the hosting company for memory limits. Should be no problem at all.
Looked at PHP garbage collecting and gc_enable() (I don't know why that would change anything).
Lots of testing, looking at the data flow.
Crying.
Conclusion: Is this type of application what PHP is for? What do you think is wrong? If you want more code/info I provide. Thank you very much.
Here is the root of your problem:
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
Note the behavior of the w open mode (emphasis mine):
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
This happens before you lock the file. What's happening is that between this fopen() call and the following flock() call, the file's content is zero length, and a reader is coming along during that time and reading the empty file.
Why doesn't this cause an error in PHP when you parse the empty string as JSON? Because json_decode() is defective, and returns null when the input is not valid JSON rather than throwing an exception. Nevermind that the string "null" is valid JSON -- json_decode() gives you no way to differentiate between the cases of valid input representing the null value and invalid input. If json_decode() actually threw an exception or triggered a PHP error (don't ask me why two error-signalling mechanisms are necessary in PHP), you would have a fantastic point to start debugging to figure out why the file is empty, and you might have solved this problem by now!
... sigh ...
PHP's "design" gives me headaches. But I digress.
To fix this whole problem, change the open mode to "cb" and ftruncate($myfile, 0) after you successfully acquire the lock.
Note the behavior of the c mode, which actually specifically mentions the approach you are using (emphasis mine):
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

Detecting if response is a BLOB in Appcelerator

I'm trying to detect whether a user has a photo assigned to their account via an API call to a web service.
If there is I can read it using:
this.responseData
If the user doesn't have an image, instead of [object TiBlob] being output from responseData I get an error string back.
here is a sample of that:
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>CA46C2292C8551EC</RequestId>.....
I'd like to be able to detect it so I can prevent an image cache taking place.
I've tried all sorts of combos, searching through strings etc. This is where I got to, but it just throws an undefined error.
var responseString = this.responseData;
if (responseString.includes('Error') == true) {
// don't request the cover builder
} else {
// handle the response
}
Any ideas how I can achieve it?
Simon
Problem was solved by using onerror and therefore there was no need to check for a BLOB

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/

How to extract messages from the dashboard in Mirth?

How to extract messages from the dashboard in Mirth?
Basically using java script, how would I extract the information from dashboard in Mirth.
For example, I am after extracting the encoded data and ACK back from the destination.
One of the thing I tried was to run the following the postprocessor. But it’s only writing raw message not the encoded.
var log1file=D:\TEST\log1.txt;
var ReportBody=(messageObject.getEncodedData());
FileUtil.write(log1file, true, ReportBody);
Any suggestions much appreciated.
Thank you.
try this...
logger.info('start post script');
var status = responseMap.get('Destination Name').getStatus();
if ((status == "ERROR" || status == "FAILURE") )
{
logger.info("Status = "+status);
var errormsg = responseMap.get('Destination Name').getMessage();
logger.info(errormsg);
}
return;
getMessage() describe exception(error) description.
You wouldn't want to extract messages from the Dashboard. The dashboard is only showing the stored history from the database it keeps.
If you want to write the encoded data to a log file as the messages are processed, move that code from your post-processor over to a transformer javascript step in the source or in a destination (the encoded data changes from source to destination if you have transformer steps or if you change from HL7 to XML, etc.)
Is it actually creating the file? You don't have quotes around your file name and the backslashes should be forward slashes.

Categories