I have simple project in ASP.NET Web site with signalr.
Code for start connection hub:
var scriptStarted = 'var myHub = $.connection.' + hubName + ';' + methodNameInitHub + '(myHub);';
$.connection.hub.error(function () {
alert("An error occured");
});
$.connection.hub.start()
.done(function () {
eval(scriptStarted);
myHub.server.registerClient($.connection.hub.id, clientIdentifier);
})
.fail(function () { alert("Could not Connect!"); });
This method is call in "methodNameInitHub + '(myHub);"
function methodInitEventHub(hub) {
if (hub) {
hub.client.addEvent = function (eventOperationName, eventType) {
$("#events").append("<li>" + eventOperationName + ", " + eventType + "</li>");
};
}
}
Code for stop connection hub:
$.connection.hub.stop();
When I load .aspx page and start hub all code execute without errors, but event from server not recieved.
After I stop and start again hub connection events begining received in client (browser)
http://clip2net.com/s/2CP2e
Why I need to restart connection hub for begin received event from server ?
Thanks.
The reason you're having issues is because you must have at least 1 client side hub function prior to calling start otherwise you will not be subscribed to the hub.
Try doing
myHub.client.foo = function() {}
prior to start.
The reason why it works after you stop then re-start the connection is because your script binds a new client method, hence allowing you to subscribe to the hub after you've restarted the connection.
Hope this helps!
Related
I am building a website based on web socket communication. Its is working fine until iOS 14 but started breaking from iOS 15. Web socket java script client is able to open connection to server, but upon trying to send a message, the connection is getting closed. Following is my html and JS code.
function start_websocket() {
connection = new WebSocket("wss://localhost/wss/");
connection.onopen = function () {
console.log('Connection Opened');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function(){
console.log("Closed");
};
connection.onmessage = function (e) {
console.log("Message Received :" + e.data);
};
}
function myFunction() {
var testText = document.getElementById("testText");
if (testText.value != "" && connection.readyState === connection.OPEN) {
connection.send("Test");
}
}
start_websocket();
myFunction() is an on-click event of a button.
A Java Websocket server is used, which will decode and send the messages based on the Data framing in https://datatracker.ietf.org/doc/html/rfc6455#section-5.
Saw different articles on the Web, but didn't found a solution to this issue. Any suggestions are much appreciated. Looking forward for your answers
Thanks in advance.
I am trying to get my proxy chrome extention to keep on/off after closing using chrome.local.storage. This does not seem to work, can anyone give some examples on how to get this kind of code working?
Right now my pac proxy works and turns on and off. The local storage does not seem to work at all, but I followed all the examples on the developer.chrome website. That does not work.
var channels;
var ny;
function endvpn() {
// turn off vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'DIRECT';\n" +
"}"
}
};
chrome.storage.local.set({ny: false});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Start Vpn";
// turn off event lisner for endvpn and start event listner to go back to startvpn
document.getElementById('vpnbtn').removeEventListener('click', endvpn, false);
document.getElementById("vpnbtn").addEventListener("click", startvpn);
}
function startvpn() {
// turn on vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'PROXY 209.127.191.180:80';\n" +
"}"
}
};
chrome.storage.local.set({ny: true});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Stop Vpn";
// turn off event lisner for startvpn and start event listner to go back to endvpn
document.getElementById('vpnbtn').removeEventListener('click', startvpn, false);
document.getElementById("vpnbtn").addEventListener("click", endvpn);
}
var rez = chrome.storage.local.get(ny);
alert(rez);
// start at startvpn
document.getElementById("vpnbtn").addEventListener("click", startvpn);
Most apis within Chrome extensions are asyncronous. See the documentation here. You can provide a callback as the second argument to the 'get' function where you can use the variable:
chrome.storage.local.get('ny', function(result){
alert(result.ny);
});
I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
var myNick = 'me';
var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');
socket.on('connect', function() {
$('#chat').addClass('connected');
});
socket.on('user message', message);
function message(from, msg) {
if (msg == 'GO') {
** EXECUTE A FUNCTION HERE **
} else { //display the message and sender
$('#lines').append($('<p>').append(from, msg));
}
}
$(document).ready(function() {
$('#send-message').submit(function() {
message(myNick, $('#messageinput').val());
socket.emit('user message', $('#messageinput').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
})(jQuery);
When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers, message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.
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
So I installed the plugin for phonegap to run google analytics. I set it up using plugman, no issues. However I am unable to establish a connection to google analytics.
document.addEventListener("deviceready", function(){
console.log('device ready');
config.gaPlugin = window.plugins.gaPlugin;
config.gaPlugin.init(console.log('ga plugin inititalized'), console.log('ga plugin failed'), config.analyticsCode, 1);
}, false);
And Instead of getting a connection back I get one response of
W/GAV2(12581): Thread[WebViewCoreThread,5,main]: Need to call initialize() and be in fallback mode to start dispatch.
I thought the init function was the initialize? However as I set it every 5 seconds the connection gets refused.
W/GAV2(12581): Thread[GAThread,5,main]: Connection to https://ssl.google-analytics.com refused
W/GAV2(12581): Thread[GAThread,5,main]: Exception sending hit: HttpHostConnectException
I have no idea what to do next, I've seen reference of needing to modify the errorhandling calls to not look for an https request, but I would like to hope its just an error in my code or a configuration error. Anyone have insight?
I use the following code which works with GAPlugin
gaInit: function() {
gaPlugin.init(gaSuccessConnect, gaFail, "UA-XXXXXX-3", 10);
},
gaSuccess: function() {
console.log('Successfully connected to Google Analytics');
},
gaSuccessConnect: function() {
console.log('Successfully initiated connection to Google Analytics');
gaTrackPage();
},
gaFail: function() {
console.warn("Failed to connect to Google Analytics");
},
gaTrackPage: function() {
gaPlugin.trackPage(gaSuccess, gaFail, "index.html");
console.log('Tracking index');
},
gaTrackPageView: function(page) {
var index = "index.html";
var trackpage = index.concat(page);
console.log('Tracking ' + page);
gaPlugin.trackPage(gaSuccess, gaFail, trackpage);
},
and call gaInit from onDeviceReady.