Skip to content
This repository has been archived by the owner on Mar 17, 2020. It is now read-only.

Commit

Permalink
Fixed automatic URL detection.
Browse files Browse the repository at this point in the history
Closes #8.
  • Loading branch information
mcollina committed Mar 3, 2014
1 parent fbd65ed commit 11664fc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 12 deletions.
46 changes: 34 additions & 12 deletions params.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,47 @@
var URL = require('url');

module.exports = function getParams(port, host, opts) {

var url = null;
var url = {};
var parsed = null;
var result = '';

if ('object' === typeof port) {
opts = port;
url = 'localhost';
host = null;
port = null;
} else if ('string' === typeof port) {
url = port;
host = port;
port = null;
opts = host;
}

if ('object' === typeof host) {
opts = host;
} else if ('object' !== typeof opts) {
opts = {};
host = null;
}

if (!host) {
host = 'localhost'
if (!host && !port && process.title === 'browser') {
host = document.URL;
}

if (!url && host && port) {
url = host + ':' + port;
url.host = host || 'localhost';
url.port = port;
url.protocol = 'ws://';

try{
parsed = URL.parse(host);
if (parsed.host) {
url.host = parsed.hostname;
url.port = parsed.port || port;
url.protocol = (parsed.protocol === 'https:') ? 'wss://' : 'ws://';
url.protocol = (parsed.protocol === 'wss:') ? 'wss://' : 'ws://';
}
} catch(e) {
}

if (url.slice(0,5).toLowerCase() != "ws://" && url.slice(0,6).toLowerCase() != "wss://") {
url = "ws://" + url;
if ('object' !== typeof opts) {
opts = {};
}

var websocketOpts = {
Expand All @@ -36,8 +52,14 @@ module.exports = function getParams(port, host, opts) {
websocketOpts.protocol = opts.protocol;
}

result = url.protocol + url.host

if (url.port) {
result += ':' + url.port
}

return {
url: url,
url: result,
opts: opts,
websocketOpts: websocketOpts
}
Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ describe('MqttClient', function() {
});
});

if (process.title === 'browser') {
describe("specifying nothing", function() {
clientTests(function() {
return mqttOverWs.createClient();
});
});
}

if (process.title === 'node') {
describe("specifying a port, secure URL and secure client options", function(){
clientTests(function(){
Expand Down

0 comments on commit 11664fc

Please sign in to comment.