Websockets not working - javascript

I have the following code in javascript:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("wss://myserver/mychannel");
myWebsocket.onmessage = function(evt) {
alert("onmessage");
}
myWebsocket.onopen = function() {
alert("onopen");
myWebsocket.send("msg0");
myWebsocket.send("msg1");
myWebsocket.send("msg2");
}
myWebsocket.onclose = function() {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
The problem is that in Firefox, the connection is closed after sending the messages, and reopened due to the command on the onclose event. If I try to send only one message on onopen, the connection keeps opened, but if I try to send more than one message, the connection shut down. This issue appears only in Firefox, not in Chrome, not in IE, not in Safari.
Can someone help me? In other browsers like IE or Chrome, once the connection is created, it keep opened until I leave the page. I have the 40.0.3v of Firefox

Try this example:
var url = "ws://echo.websocket.org";
if (!window.WebSocket) alert("WebSocket not supported by this browser");
var myWebSocket = {
connect: function () {
var location = url
this._ws = new WebSocket(location);
this._ws.onopen = this._onopen;
this._ws.onmessage = this._onmessage;
this._ws.onclose = this._onclose;
this._ws.onerror = this._onerror;
},
_onopen: function () {
console.debug("WebSocket Connected");
},
_onmessage: function (message) {
console.debug("Message Recieved: " + message.data);
},
_onclose: function () {
console.debug("WebSocket Closed");
kiosk.connect();
},
_onerror: function (e) {
console.debug("Error occured: " + e);
},
_send: function (message) {
console.debug("Message Send: " + message);
if (this._ws) this._ws.send(message);
}
};
myWebSocket.connect();
setInterval(function() {
myWebSocket._send('msg1');
}, 5000);
Here is a JSFidlle

It may be that your support var is not behaving as you expect. The following code works in FireFox without closing the connection:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("ws://echo.websocket.org/");
myWebsocket.onmessage = function (evt) {
alert("onmessage");
}
myWebsocket.onopen = function () {
alert("onopen");
myWebsocket.send("a test message");
}
myWebsocket.onclose = function () {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
Example Fiddle
You can use the tool on Websocket.org to make sure websockets are
working correctly in your browser.
Or (although your issue is with FF) you can use the steps listed
here to debug websockets.

Try it.
var WS = window.WebSocket || window.MozWebSocket;
if (WS){
var websocket = new WS("wss://myserver/mychannel");
}

Related

Connection has not been fully initialized

In my application the following console error occurs when I navigate to another page.
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
In layout page the scripts are in the following order.
#Styles.Render("~/Content/themes/base/jqueryUi")
#Styles.Render("~/Content/customCss")
#Scripts.Render("~/Scripts/jQuery")
#Scripts.Render("~/Scripts/customScripts")
<script src="/signalr/hubs"></script>
var progressHub = $.connection.parallelProcessing;
var flagDownload = true;
$(function() {
progressHub.client.updateProgresssBar = function(progressPercentage, downloadedSize, totalFileSize) {
debugger
downloadProgress("", "", "");
$("#downloading-progress").dialog("open");
var progressObj = $("#progressBar").data("ejProgressBar");
progressObj.option("text", progressPercentage + " %");
progressObj.option("percentage", progressPercentage);
$(".received").html("(" + downloadedSize + " ");
$(".total-size").html("of " + totalFileSize + ")");
flagDownload = true;
if (progressPercentage == 100)
$("#downloading-progress").dialog("close");
};
progressHub.client.noNetConnection = function() {
if (flagDownload) {
flagDownload = false;
showalertdownload("#Message.Nointernetconnection");
}
};
progressHub.client.closeProgressDialog = function() {
$("#downloading-progress").dialog("close");
enableEvents();
};
$.connection.hub.start().done(function () {
});
});
function updateConnectionID() {
progressHub.server.updateConnectionID();
}
Please let me know is ther any solution to resolve this issue.Thanks in advance.
Basing my answer on your error message, it seems you are trying to access your connection or hub without waiting for it to be initialized.
Taken from the ASP.NET SignalR Github wiki:
// This callback will only run once
connection.start().done(function() {
console.log("connection started!");
});
A more complete and detailed example to be found on ASP.NET website

firefox addon: quit-application observer not working

I've been trying to use observers for a while now, but it seems like I cannot get them to work. I put the observe function in different modules of my extension, and also different parts of my code. Registering it from everywhere but it seems like every way that I tried was just a deadened. I can't get it to work. My goal is to listen for when a user exits from Firefox so I can clear preferences objects of my addon. As of now my observer is in bootstrap.js, and this is how I implemented it. I implemented my observe function this way because it was mentioned in this stackoverflow post that this is the right way to observe for quit-application notification. On a side note observers registered gets printed in console log but "oh observing" doesn't.
function myObserver()
{
this.register();
}
myObserver.prototype = {
observe: function(subject, topic, data) {
console.log("oh observing!!");
if (topic == "app-startup" || topic == "profile-after-change") {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "quit-application", false);
}
else if (topic == "quit-application-requested" || topic == "quit-application")
{
console.log("browser closing");
alert('hello');
myextension.Utils.prefService.clearUserPref("questionType");
myextension.Utils.prefService.clearUserPref("clickThrough");
this.unregister();
}
},
register: function() {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "quit-application-requested",false);
observerService.addObserver(this, "quit-application",false);
observerService.addObserver(this, "app-startup", false);
observerService.addObserver(this, "profile-after-change", false);
console.log("observers registered");
},
unregister: function() {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, "quit-application-requested");
console.log("unregistering obs");
}
}
This is my startup function:
function startup(data, reason) {
Components.utils.import("chrome://ext/content/commons.jsm");
let wm = Cc["#mozilla.org/appshell/window-mediator;1"].
getService(Ci.nsIWindowMediator);
let windows = wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
let domWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
WindowListener.setupBrowserUI(domWindow);
}
// Wait for any new browser windows to open
wm.addListener(WindowListener);
}
and this is my setupBrowserUI function in which I register the observer:
setupBrowserUI: function(domWindow) {
extension.onLoad(domWindow.gBrowser);
observer = new myObserver();
}
The easy way:
https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
let observer = {
observe: function() {
dump("oh observing")
}
};
function startup(data, reason)
{
Services.obs.addObserver(observer, "*", false);
observer.observe();
}
My suggest is create a log file with the preferences; to output dump calls instead to a file, set browser.dom.window.dump.file to the file destination where the log should be created and restart the application.
https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Preference_reference/browser.dom.window.dump.file

My WebSocket doesnt work in Opera/Midori

everyone I'm creating an "Object" to manage all information about my socket connection but I've some problems about browser compatibilities
$(document).ready(function(){
socket.connect();
socket.connection.onopen = function(){
console.log('Connected '+ socket.connection.readyState);
//Show 1 for every browser
};
socket.connection.onmessage = function(event){
console.log('Some message '+event.data);
//Firefox / Chrome Fine
//Midori/Opera doesnt show this message (console)
};
});
var socket ={
dataConnection: {
url:"myURL",
param:"myParam"
},
connection: "",
connect: function(){
try{
this.connection = new WebSocket(this.dataConnection.url+"/"+this.dataConnection.param);
}catch(error){
console.log('Something wrong ' + error.message);
}
}
};
I don't understand Wy It works fine (FF and Chrome), Can you give an advice?

How to enable OpenTok Plugin for Internet Explorer

I am trying to implement open tok for my video chat application.
I am using opentok.min.js v 2.2.9 with php SDK. It is working fine with google chrome and firefox.
According to their announcements, it should work in IE with 32 bit OS.
https://tokbox.com/opentok/libraries/client/js/release-notes.html
But it is not working for me at any version of IE.
Anybody knows how to implement it for IE?
// Detect whether this browser is IE
var isNotIE = function isIE() {
var userAgent = window.navigator.userAgent.toLowerCase(),
appName = window.navigator.appName;
return !(appName === 'Microsoft Internet Explorer' || // IE <= 10
(appName === 'Netscape' && userAgent.indexOf('trident') > -1)); // IE >= 11
};
function connect() {
if (isNotIE() && OT.checkSystemRequirements()) {
session = OT.initSession(apiKey, sessionId);
sendMessage("Session has initialized. Connecting to session ... ");
session.on({
streamCreated: function(event) {
sendMessage("New stream in the session: " + event.stream.streamId);
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
},
streamDestroyed: function(event) {
sendMessage("Stream stopped streaming. Reason: " + event.reason)
},
signal: function(event) {
sendMessage("Signal sent from connection " + event.from.id);
// Process the event.data property, if there is any data.
}
});
session.connect(token, function(error) {
if (error) {
sendMessage("Error connecting: ", error.code, error.message);
} else {
sendMessage("Connected to the session successfully.");
displayBtn('connected');
}
});
}else{
sendMessage("What Should I do if it is IE?? :(");
}
}
function sendMessage(message) {
message = '<br>' + message;
$("#statusbox").append(message);
}
Now that IE versions 8-11 are supported by the plugin, you shouldn't need to switch on the isNotIE() && OT.checkSystemRequirements() condition, you can just use the same code path for all of those browsers.
It may still be a good idea to detect IE versions that are outside that range to let the user know that the feature of your application that uses OpenTok is not supported with some suggestions to upgrade/install.
Otherwise, one code suggestion: In the streamCreated event handler, rather than using 4 lines of code to create a new DOM element and then add it to a container, you can use the insertMode: "append" option. This works for both Publishers and Subscribers.
Before:
var parentDiv = document.getElementById(subscriberElement);
var replacementDiv = document.createElement("div"); // Create a div for the publisher to replace
replacementDiv.id = "opentok_subscriber";
parentDiv.appendChild(replacementDiv);
subscriber = session.subscribe(event.stream, replacementDiv, subscriberProperties, function(error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
}
});
After:
subscriber = session.subscribe(event.stream, document.getElementById(subscriberElement), { insertMode: "append" }, function (error) {
if (error) {
console.log(error);
} else {
console.log("Subscriber added.");
// Set the ID of the DOM element if thats used elsewhere in the code
subscriber.element.id = "opentok_subscriber";
}
});

Best Practise to check Internet connection in javascript

I am using Ajax to check my internet connection after every few second for my application which is using IE instance. But due to low bandwidth my internet explorer is crashing.
What best practise can be followed to check the internet connection so that it prevent crashing of internet explorer and boost performance ?
I am using the following code to check my internet connection.
The explanation of which is given at: -
http://tomriley.net/blog/archives/111 from where I get the jquery file.
(function ($) {
$.fn.checkNet = function (intCheckInterval, strCheckURL) {
if (typeof (intCheckInterval) === 'undefined') {
var intCheckInterval = 5
} if (typeof (strCheckURL) === 'undefined') {
var strCheckURL = window.location
} else if (strCheckURL.indexOf('http') === -1) {
var strCheckURL = 'http://' + strCheckURL
} intCheckInterval = intCheckInterval * 1000; function doRequest(strCheckURL) {
$.ajax({ url: strCheckURL, cache: false, success: function () {
if ($('#netWarn').length) {
$('#netWarn').fadeOut()
} $('.tempDisabled').removeAttr('disabled').removeClass('tempDisabled')
}, error: function () {
if (!$('#netWarn').length) {
$('body').prepend('<p id="netWarn">No internet connection detected, some features will be re-enabled when a connection is detected. </p>'); $('#netWarn').fadeIn()
}
}
})
} setInterval(function () {
doRequest(strCheckURL)
}, intCheckInterval)
}
})(jQuery);
my plugin takes an argument for the length of time between the requests. So, if you want a 10sec interval between requests, call it with this code:
$.fn.checkNet(10);
...after you've included the plugin. I uploaded a new version recently which works much more efficiently.

Categories