I´m pretty new in the whole JS and node.js and npm thing and im trying to use a mqtt broker in a project I have for a class, so I installed the mqtt module from npm and to give me an idea of how it works I ran the example in the npm page but it doesn´t seem to work, it just hangs without ever printing the "hello mqtt" it says it should? im sure im missing something but i really don´t know what.
The code is:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
the page I got it from is https://www.npmjs.com/package/mqtt
i also tried using my own broker but it also doesnt work.
This could be so many things, but the most likely is that you are failing to connect to the broker.
The sample code has no error handling at all so it's not going to tell you when it fails to connect. Try the following code which should tell you what's going on.
var mqtt = require('mqtt')
var options = {
connectTimeout: 10000
};
var client = mqtt.connect('mqtt://test.mosquitto.org',options)
client.on('connect', function () {
console.log("connected");
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('error', function(err){
console.log("error %j", err);
});
client.on('close',function(){
console.log("client disconnected");
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I've wound the connection timeout down to 10 seconds from the default 30 so you can see it fail quicker.
Related
I have been trying to setup a wss server using nodejs, and have encountered a problem when trying to connect to it using chrome. The problem still occurs with all extensions disabled and in an incognito window so I've ruled that out as the problem.
When trying to connect using chrome, I get the error:
WebSocket connection to 'wss://www.domain-name.com/' failed:
with no reason given. On the server, socket.on('close') is called immediately with description "Connection dropped by remote peer" The close event has wasClean = false. This error does not occur when connecting from safari and Firefox so I'm not really sure where to look to see what's causing it. It's running on AWS Lightsail, and through an Apache proxy server.
The client code:
var socket = new WebSocket("wss://www.domain-name.com", 'JSON')
socket.onopen = function (event) {
console.log('open');
socket.send('socket opened')};
socket.onclose = function (event) {
console.log(event)};
socket.onmessage = function(message) {
console.log('receiving message from server...')};
And the server code:
const WebSocketServer = require('websocket').server;
app = express()
var server = app.listen(3000, () => {
console.log('Server started');
});
app.use(express.static('public'));
var wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request){
console.log('New connection');
var connection = request.accept(null, request.origin);
connection.send('welcome from server...');
connection.on('message', function(message){
console.log(message)};
connection.on('close', function(reasonCode, description) {
console.log('disconnecting', reasonCode, description);
});
});
I also got the same error before switching to a secure WebSocket server. Any help would be appreciated, I've run out of places to look and ways to try and get more information to help out what the problem is.
EDIT: it seems to work on chrome on my phone, but not on chrome on my friends phone?
The problem was not specifying the protocol when accepting the connection. After about 20 hours working on the same bug and implementing an SSL certificate to get it to work, I changed:
request.accept(null, request.origin);
to:
request.accept('json', request.origin);
For some reason the chrome gives a really unhelpful error message. Microsoft edge the same error occurs, but gives a much more helpful error message so I could work out what was going on.
In my case, this was caused by passing an unused options value as the third parameter to the WebSocket constructor. The options parameter is supported by Node.js's ws module but not by browsers; however, instead of displaying a clean error message, Chrome closed the connection without a good description.
I'm running protractor on my windows VM and need to execute some commands on a linux VM. I'm trying to use SSH to do the same. I've tried using 'simple-ssh', 'remote-exec' and 'ssh-exec. The problem with all of them is the same, the protractor test completes without any error but the SSH connection is not established. Strangely it doesn't throw any error as well, I've tried giving wrong IP, but still, no error is thrown. I've tried SSH over python with same machine, it works flawlessly.
here is a piece of code from documentation that I directly tried to use.
var ssh = new SSH({
host: 'xx.xx.xxx.xx',
user: 'xxxxx',
pass: 'xxxxx'
});
ssh.exec('ls -lh', {
out: function(stdout) {
console.log(stdout);
}
}).start();
Figured it out.
I used ssh2 package to establish an interactive SSH session. Then I synchronized it with jasmine using done() in jasmine 2.
Used Maciej Ciach's solution for solving sync problem.
Here's an 'It' block that runs flawlessly
it("trying ssh connection", function (done) {
var conn = new Client();
conn.on('ready', function () {
console.log('Client :: ready');
conn.shell(function (err, stream) {
if (err) throw err;
stream.on('close', function () {
console.log('Stream :: close');
conn.end();
}).on('data', function (data) {
console.log('OUTPUT: ' + data);
});
stream.end('ls \nexit\n');
done();
});
}).connect({
host: 'xx.xx.xxx.xx',
port: 22,
username: 'x',
privateKey: require('fs').readFileSync('file_path')
});
})
Obviously, you need to add your public ssh key to the list of trusted keys on your server first.
You can read about it here.
If you are on windows then execute those commands in Powershell.
I would like to conenct an MQTT broker with Javascript in order to subscript to a topic and publish messages. The connection needs to be done through tcp on port 1883. I am using MQTT.js library. The front end is in angularjs.
The example followed is the one in MQTT.js page, though the connection cannot be achieved. Could anyone please help?
Connection through index.html:
<script src="../node_modules/mqtt/browserMqtt.js"></script>
Code for connection:
var client = mqtt.connect('url.com:1883',{clientId :'client1', clean: true});
client.on('connect', function () {
console.log("onsubscribe");
client.subscribe('votingSignals', function (err) {
if (!err) {
console.log("onsubscribe");
client.publish('votingSignals', 'start')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
The error displayed is:
WebSocket connection to 'ws://url.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
From a web browser you can ONLY use MQTT over Websockets, not native MQTT (over TCP).
This is because the browser will not let you open a normal socket.
var zapClient = require('zaproxy');
const zapOptions = {
key : 'abcdefghijklmn',
proxy : 'http://localhost:8090/'
};
const zaproxy = new zapClient(zapOptions);
zaproxy.spider.scan("https://www.google.co.in");
i am trying to run above code i am getting :
(node:8380) UnhandledPromiseRejectionWarning: RequestError: Error: socket hang up error.
i have tried socket hang up error with nodejs and "Request error: Socket hang up" with nodeJS on Amazon EC2 didn't help.
I believe changing the last line of your code to this should fix the problem:
zaproxy.spider.scan("https://www.google.co.in", (err, res) => {
if (err) throw err;
//do something with res here
});
//can't do anything with res here
Also check the zap.log file - that might be logging errors which by default are not reported to the client (for security reasons - this can be disabled for testing)
I would like to fiddle with websockets a bit. I installed a Ruby gem called "websocket-ruby" (https://github.com/imanel/websocket-ruby) I started a pry / IRB session and typed:
require "websocket"
#handshake = WebSocket::Handshake::Server.new(:host => "localhost", :port => 8080,:secure=>true)
This starts a websocket server as far as I know. Then I opened in my browser the Javascript HTML page which attempt to connect to the server:
<!doctype html>
<html lang="en">
<head>
<title>Websocket Client</title>
</head>
<body>
<script>
var exampleSocket = new WebSocket("wss://localhost:8080");
exampleSocket.onopen = function (event) {
exampleSocket.send("Can you hear me?");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
</script>
</body>
</html>
But it says in the console log:
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried different ports both in server and in the client respectively: 8081, 12345, but I always get this error message.
I have some idea about websocket and javascript, but not websocket-ruby.
I hope it will helpful you.
In nodejs.. server.js file, write below code
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
console.log("websocket Server is Running...");
wss.on('connection', function connection(ws) {
// Store the remote systems IP address as "remoteIp".
var remoteIp = ws.upgradeReq.connection.remoteAddress;
// Print a log with the IP of the client that connected.
console.log('Connection received: ', remoteIp);
// Add a listener which listens for the "message" event.
// When a "message" event is received, take the contents
// of the message and pass it to the broadcast() function.
ws.on('message', wss.broadcast);
});
wss.broadcast = function(msg) {
wss.clients.forEach(function each(client) {
client.send(msg);
})
};
In javascript...
var SERVER_URL = 'ws://localhost:8100';
//instead of localhost you can also use IP address of your system
var ws;
function connect() {
alert('connect');
ws = new WebSocket(SERVER_URL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// with the new message.
console.log(msg);
}
/** This is the scope function that is called when a users hits send. */
function sendMessage{
ws.send(msg);
};
connect();
in html use one button to send message to websocket server
<button onclick="sendMessage('Hi Websocket')">send message</button>
To the best of my knowledge, the Ruby code you presented does not start a Websocket server... what it does is initiate a server-side parser.
To start a server you need to use an actual websocket server.
ActionCable (with Rails) uses the websocket-ruby library to parse websocket events and it uses nio4r to operate the actual server.
Faye have a similar solution and em-websockets use the websocket-ruby gem with EventMachine.
Other Ruby Websocket servers include Iodine, which uses the C library facil.io. Iodine is used by the framework plezi as well as independently.
Since you were trying to run an echo server, here's a quick example using the Plezi framework (you can use it as middleware in Sinatra or Rails)...
...place the following in a config.ru file:
require 'plezi'
class WebsocketSample
# HTTP index
def index
'Hello World!'
end
# called when Websocket data is recieved
#
# data is a string that contains binary or UTF8 (message dependent) data.
def on_message(data)
puts "Websocket got: #{data}"
write data
end
end
Plezi.route '/', WebsocketSample
run Plezi.app
To run the server, call (ignore the $ sign, it marks this code as terminal code):
$ iodine
notice: Iodine requires a BSD / Unix / Linux machine, such as macOS, Ubuntu, etc'. It won't work on windows.