Event Source Live streaming in Ruby on rails onError method - javascript

I'm trying to implement basic Rails 4 code with Event Wource API & Action controller live. Everything is fine but I'm not able to reach event listener.
Controller code:
class HomeController < ApplicationController
include ActionController::Live
def tester
response.headers["Content-Type"] = "text/event-stream"
3.times do |n|
response.stream.write "message: hellow world! \n\n"
sleep 2
end
end
Js code:
var evSource = new EventSource("/home/tester");
evSource.onopen = function (e) {
console.log("OPEN state \n"+e.data);
};
evSource.addEventListener('message',function(e){
console.log("EventListener .. code..");
},false);
evSource.onerror = function (e) {
console.log("Error State \n\n"+e.data);
};
When I reload the page, my console output was "OPEN state" & then "Error State". Event listener code was not displaying.
When I'm curling the page, "message: Hellow world!" was displaying.
I changed in development.rb
config.cache_classes = true
config.eager_load = true
My browsers are chrome & firefox are latest versions, so no issues with them
Where I'm missing? suggestions please!

Event format for server-sent events is
"data: message text\n\n"
So, in your case it should be like:
response.stream.write "data: hello world! \n\n"
Check this MDN page for reference.

Related

Display error html for offline mode in Angular 6

I have an app that could go in to offline mode. For that i have implemented a HostListener which listens to apps events.
#HostListener('window:offline', ['$event']) onOffline() {
this.isOnline = false;
}
This works fine and I display an error message:
<div *ngIf="!isOnline">
<div class="network-div">
<mat-icon class="network-icon">cloud_off</mat-icon>
</div>
<p class="network-text">Network error - unable to connect.
Please try again or contact support if error persists, contact the NCR
support desk.</p>
</div>
When i go offline, i get the desired message, but now that internet is down, when i refresh, I get the usual google error message with that dinasour.
I can't render the error HTML in my angular component anymore since its running in offline mode. I need to render the above HTML when i refresh.
When i click on 'Offline' of developer tool, i render an HTML and below is the screenshot:
When i refresh the same page (still in offline mode),i receive the following:
How should i handle this?
if you are registering service worker you can try:
ngOnInit() {
if (!navigator.onLine) {
this.isOnline = false;
}
}
note that you should check it after build your project and serve it.
About the browser's cache visit: How to Enable Offline Browsing in Firefox
If you attach the event listener to document.body on a browser, Chrome couldn't work.
You can register listeners for these events:
using addEventListener on the window, document, or document.body
by setting .onoffline properties on document or document.body to a
JavaScript Function object.
by specifying onoffline="..."
attributes on the tag in the HTML markup.
A javascript
window.addEventListener('load', function() {
var status = document.getElementById("status");
var log = document.getElementById("log");
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
status.className = condition;
status.innerHTML = condition.toUpperCase();
log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});
Go to the networks tab in your developer tools and see if the SW is registered and offline works by running Audit.

VS2015 Cordova Sms Plugin Sms.Send doesn't work in Index.JS (ondeviceReady)

I'm new to Cordova, any help would be appreciated.
I created a new Cordova Project in VS2015 and added the Cordova SMS plugin to my project (https://www.npmjs.com/package/cordova-sms-plugin).
I added this code to /www/scripts/index.js function onDeviceReady (as per documentiation for plugin):
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
var numberString = "aoeuaeu";
var bypassAppChooser = true;
//CONFIGURATION
var options = {
replaceLineBreaks: false,
android: {
intent: 'INTENT' // send SMS with the native android SMS messaging
}
};
var successSMS = function () { alert('Message sent successfully'); };
var errorSMS = function (e) { alert('Message Failed:' + e); };
sms.send("0811231234", "Testing123", options, successSMS, errorSMS);
I debug the project using Debug, Android, Ripple - Nexus (Galaxy) selected options. When I place a breakpoint on the sms.send line of code and I add a watch for 'sms.send', I can see the object exists.
When I single step, this line in sms.js seems to be the last line that executes:
// fire
exec(
success,
failure,
'Sms',
'send', [phone, message, androidIntent, replaceLineBreaks]
);
I then get the following error message in Ripple:
'Sms.send We seem to be missing some stuff :( What is kinda cool though you can fill in the textarea to pass a json object to the callback you want to execute).'
I can see that all of the objects in that line is defined (success, failure, phone, message, androidIntent, replaceLineBreaks). When I 'step into' this line, it continues to execute code in ripple.js, but it becomes hard to follow for a person, since there are no line breaks in this file.
What am I doing wrong? I've read through all the documentation I can find & searched stackoverflow questions and can't seem to find any solutions to the problem.
I've uploaded this entire project (zipped), which can be downloaded at:
https://drive.google.com/file/d/0BwWgTMh-JLbfNHV0MlE5Yk5IZ3M/view?usp=sharing
Thanks in advance
Thank you Cordova team at Microsoft for helping me with an answer:
"Ripple has the ability to emulate some but not all plugins. SMS is not one of the plugins that it can fully emulate. However, in the message that pops up, you do have the ability to hit the Success or Fail buttons which will report back to the app that it was successful or not in sending the SMS. While that doesn’t actually send a message, it does let you test your app to see how it behaves for different results.
I tried the bit of sample code you included in the first email. In Ripple, I was able to change the alert by hitting the different buttons.
Trying other deployment methods, in both the VS Android Emulator and the Google Emulator they showed failure alert messages that they don’t support SMS messages. I then launched it on an Android phone device and it said it was successful.
So I believe your options are mainly using Ripple to fake sending of messages or using a device for testing."

oracle forms javascript integration

I'm trying to experiment with the new javascript integration features of oracle forms 11g.
My current configuration:
Forms 11.1.2.2.0
Weblogic 10.3.6.0
JRE 1.7u55
Windows 7 x64
I installed the demo at http://www.oracle.com/webfolder/technetwork/tutorials/obe/forms/11g/jsinteg/formsjsinteg/setup.htm
This is only working from FORMS to Javascript but not the other way. i.e Javascript to FORMS.
I thought all the additional Javascripts et al in it is making it difficult for me to know what's happening so I created a simpler html page with a textbox, a button and an anchor for onclick along with the applet in iFrame.
Again the code is working from FORMS to javascript but not the other way.
This line is not working:
window.frames['forms_iframe'].contentDocument.document.forms_applet.raiseEvent(event, payload);
UPDATE:
I changed it so the applet and all the testing code is placed in one html. and added some try catch code to my calls.
changed my call to:
function frmEvent (event, payload) {
alert(event+", "+ payload);
event = "PUSH";
try {
document.forms_applet.raiseEvent(event, payload);
}
catch(err) {
var txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
Now I get in IE
liveconnect call for applet id 1 is not allowed in this jvm instance
in chrome, it says:
Error calling method on NPObject
I think the whole problem is with this liveconnect changes to java runtime... wondering what else to do to solve this issue now.
Lower the Java security setting from High (only authorized Java script can be run) to Medium (Prompt before unauthorized Java script), user will receive a prompt and then the worksheet can be opened just
fine. It's due to higher security requirement with JRE 7u45
https://blogs.oracle.com/java-platform-group/entry/updated_security_baseline_7u45_impacts

PHP WebSockets with Ratchet - example doesn't work

Here's some background first.
My aim is to use Ratchet WebSockets to create two-way client-server communication.
I have installed ratchet and accompanying software, as described here.
I have successfully created a Hello World application as described here.
Now I am trying to create Push functionality using this tutorial. I have copied the code, modifying it slightly (modifications noted in code comments below), installed the ZMQ library (latest version, added it to php.ini, show up in php -m - in short, it's installed correctly). But the WebSockets don't work.
I will give my testing process with real live links to my domain below, so you can check it yourself.
My push server is exactly the same as the one in their tutorial, with the IP changed to my server's IP. I run this through SSH and it seems to connect correctly.
My Pusher class is in the MyApp namespace, same code and same relative location as in their tutorial.
My post.php is slightly modified because there's no need to bother with MySQL queries:
$entryData = array( //hard-coded content of $entryData for simplicity
'cat' => "macka"
, 'title' => "naslov"
, 'article' => "tekst"
, 'when' => time()
);
// This is our new stuff
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://light-speed-games.com:5555"); //my domain, still using port 5555 as in their example
$socket->send(json_encode($entryData));
This file is located here.
My client.php is the same as theirs, except I had to add a little fix for IE to work with when.js. My problem is browser-independent and the same as it was before the fix was added.
<script>
window.define = function(factory) { //my addition
try{ delete window.define; } catch(e){ window.define = void 0; } // IE
window.when = factory();
};
window.define.amd = {};
</script>
<script src="/apps/scripts/when.js"></script>
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session(
'ws://light-speed-games.com:8080' // The host (our Ratchet WebSocket server) to connect to
, function() { // Once the connection has been established
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
, function() { // When the connection is closed
console.warn('WebSocket connection closed');
}
, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
'skipSubprotocolCheck': true
}
);
</script>
This file is located here.
In theory, what should happen is this (for example): I open client.php in Chrome with console switched on; then I open post.php in Firefox; Chrome's console should show the message 'New article published...' etc (from the conn.subscribe function in client.php). However, when I do this, nothing happens. The connection remains open (doesn't show the 'connection closed' error until I switch off push-server.php through SSH). The console remains empty.
I think that's all the relevant info from the last couple of days, a large portion of which I've spent on trying to figure this out. However, I've been unable to even make sure if the problem is with the code or with some server configuration setting I may be unaware of. So, I come to you hoping someone will point me in the right direction.
Important edit
I'm pretty sure the problem is with the Autobahn.js method conn.subscribe not working properly. The connection is being established. When I change the code to:
function() { // Once the connection has been established
console.log('Connection established');
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
Then Connection established is shown in the console correctly. So I believe we need to troubleshoot the subscribe method. If someone can explain to me how it works, and what exactly "topic" and "data" are supposed to be, it would be of great help. The Autobahn documentation uses a URL as an argument for this method (see here).
Your client is looking for an article in kittensCategory, but you are sending category macka. Try this:
$entryData = array(
'cat' => "kittensCategory",
'title' => "naslov",
'article' => "tekst",
'when' => time()
);
Is it correct to see your host light-speed-games.com on port 8080 is not functioning? If not, I would suggest to fix this as it is likely its causing your issues.

Server-Sent Event method not handled by Firefox

I am building a rails application using ActionController::Live and and Custom SSE library,
My server is puma, and rails version is 4 this is my code in my controller:
include ActionController::Live
def index
response.headers['Content-Type'] = 'text/event-stream'
ss = Reloader::SSE.new(response.stream)
100.times {
ss.write({ :message => "just checking"}, :event => 'refresh')
sleep 10
}
ensure
ss.close
end
and this is my Library sse.rb file
class SSE
def initialize io
#io = io
end
def write object, options = {}
options.each do |k,v|
#io.write "#{k}: #{v}\n"
end
#io.write "data: #{JSON.dump(object)}\n\n"
end
def close
#io.close
end
end
and this is my application.js file to handle SSE
$(document).ready(function() {
setTimeout(function() {
var source = new EventSource('/');
source.addEventListener('refresh', function(e) {
window.location.reload();
});
}, 1);
});
I am following the tutorial from this site http://tenderlovemaking.com/2012/07/30/is-it-live.html
Whenever I load my Firefox page, it is not handling the stream, instead it is showing the option to download the stream as text file. I don't why this is happening.
My understanding here of the SSE is at fault here, the SSE and the page/controller i am working, i took them as one, i was trying to view the controller of SSE in firefox or chrome. Very poor understanding on my part of the SSE. SSE controller and the page i want to trigger events are completely different. I got this answer at the end of this tutorial
http://tenderlovemaking.com/2012/07/30/is-it-live.html
Hope you guys got it too.

Categories

Resources