Skip to content

Instantly share code, notes, and snippets.

@ba55ie
Last active February 20, 2019 07:11
Show Gist options
  • Save ba55ie/08d5659a4cb547fd3abab7f3abed0958 to your computer and use it in GitHub Desktop.
Save ba55ie/08d5659a4cb547fd3abab7f3abed0958 to your computer and use it in GitHub Desktop.
Node.js SignalR V2.2.0 client
'use strict';
const jsdom = require('jsdom');
const window = jsdom.jsdom().defaultView;
const url = 'http://YOUR_SIGNALR_URL'; // Used for CORS
const hubs = 'http://YOUR_SIGNALR_HUBS_URL';
function loadScript(src) {
return new Promise((resolve, reject) => {
let script = window.document.createElement('script');
script.src = src;
window.document.body.appendChild(script);
script.onload = (e) => resolve(e);
script.onerror = (err) => reject(err);
});
}
function connect() {
let connection = window.$.connection;
let hub = connection.YOUR_HUB_NAME;
function start() {
connection
.hub
.start({ transport: 'auto', waitForPageLoad: false })
.done(() => {
// Send a message to the server
// It depends on the hub how the methods are named
hub.server.subscribe('YOUR_MESSAGE');
console.log('connection started!', connection.hub.id);
});
}
connection.hub.url = url; // Enable CORS
connection.hub.logging = true;
// Hub publish callback
// It depends on the hub how the methods are named
hub.client.publish = (data) => {
console.log('Hub published data: ', data);
};
// Disconnected callback
connection
.hub
.disconnected(() => {
console.log('disconnected...');
setTimeout(() => start(), 10000); // Restart connection after 10 seconds.
});
// Start the connection
start();
}
// Load jQuery, SignalR, the hub and then connect
jsdom.jQueryify(window, 'http://code.jquery.com/jquery-2.2.2.min.js', () => {
loadScript('http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js')
.then(() => loadScript(hubs))
.then(() => connect())
.catch((error) => console.log('error', error));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment