Messages not received using node.js MQTT client with socket.io - node.js

I am using socket.io, node.js and the node.js MQTT client to connect to a broker running on A-MQ from an HTMLS page. I can successfully connect to the broker and subscribe to the topics I need, but I never get any messages back from the topics even though several are enqueued.
Here is my code:
subscribe.js
var sys = require('sys');
var net = require('net');
var mqtt = require('mqtt');
var io = require('socket.io').listen(5000);
io.set('origins', '*:*');
var client = mqtt.connect("mqtt:admin:admin#//localhost:1883");
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function (data) {
console.log('Subscribing to '+data.topic);
socket.join(data.topic);
client.subscribe(data.topic);
});
});
client.addListener('mqttData', function(topic, payload){
sys.puts(topic+'='+payload);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(payload)});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>IoT Demo</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:5000');
socket.on('connect', function () {
socket.on('mqtt', function (msg) {
var elmarr=msg.topic.split("/");
var elm=elmarr[3];
console.log(msg.topic+' '+msg.payload);
$('#'.concat(elm)).html(msg.payload);
});
socket.emit('subscribe',{topic:'customerenter'});
socket.emit('subscribe',{topic:'customermove'});
socket.emit('subscribe',{topic:'customerexit'});
});
</script>
</head>
<body>
<div style="position: absolute; top: 5px; left: 5px;">
</div>
</body>
</html>
When I debug in Chrome,
socket.on('mqtt', function (msg)
is never executed.
Any thoughts?
Thanks,
Ted

Assuming you using the Mqtt client from npm (https://www.npmjs.com/package/mqtt) then the mqtt client should have a on 'message' callback set to handle incoming messages, not mqttData listener
client.on('message', function(topic, message){
sys.puts(topic+'='+message);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(message)});
});

Related

I can't connect to server(AWS Amazon EC2) using Socket.io with Phonegap on iOS device

I uploaded a server-side code to AWS Amazon EC2 with node.js and socket.io.
When I connect to that server from browser(both on desktop and ios safari), it works with no problem.
But, when I create a cordova project and modify some of the codes to comply with cordova, get it run on ios device, it doesn't work!
I tried
<access origin="My-server-side-url-comes-here*"/>
but it didn't solve the problem.
Also, i opened up port :9000 on EC2 for TCP connection.
It seems that socket = io.connect(serverUrl); is causing problem..
I've been struggling to get this work for days now...
Can anyone tell me how to get socket.io work with external host, phonegap, and ios?
server side code uploaded to AWS Amazon EC2 (app.js)
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function (request, response){
console.log('server created');
}).listen(9000, function(){
console.log('server running!');
});
var io = socketio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('msg', function(data){
console.log(data);
io.sockets.emit('msg_by_server', "server got your msg:"+data);
});
});
client-side code that works with desktop browsers and iPhone safari(which works fine) (index.html)
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket;
var serverUrl = "sampleURL.compute.amazonaws.com:9000";
window.onload = function(){
socket = io.connect(serverUrl);
socket.on('msg_by_server', function(data){
alert(data);
});
}
var sendMessage = function(){
socket.emit('msg', 'msg from client');
}
</script>
</head>
<body>
<button onclick = 'sendMessage();'>Message Send</button>
</body>
</html>
different client-side code used for phonegap(which doesn't work) (index.html)
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
alert('check1');
var socket="";
app.initialize();
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('check2'); // shows up
var serverUrl = "sameURL.compute.amazonaws.com:9000";
socket =io.connect(serverUrl);
alert('check3'); // doesn't show up
socket.on('connect', function(){
socket.on('msg_by_server', function(data){
alert(data);
});
socket.emit('msg', 'msg from client')
});
}
var sendMessage = function(){
alert(socket);
socket.emit('msg', 'msg from client');
};
</script>
</head>
<body onload="onDeviceReady();">
<!--
i put onload="onDeviceReady();" because
document.addEventListener("deviceready", onDeviceReady, false);
doesn't seem to work for some reason..
-->
<button onclick = 'sendMessage();'>amessageSend</button>
</body>
</html>

NodeJS and socket.io can't send message

today I follow an tutorial by Gonzalo Ayuso at http://gonzalo123.com/2011/05/23/real-time-notifications-part-ii-now-with-node-js-and-socket-io/ but it can't send the message
Here is my server.js
var http = require('http');
var io = require('socket.io');
server = http.createServer(function(req, res){
});
server.listen(8000);
//socket.io
var socket = io.listen(server);
socket.set('transports', ['websocket']);
console.log("Start");
socket.on('connection', function(client){
client.on('message', function(msg){
console.log(msg);
socket.broadcast(msg);
})
});
and the client.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
</head>
<body>
<p><a id='customAlert' href="#" onclick='socket.send("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='socket.send("customAlert2")'>publish customAlert2</a></p>
<script src="http://localhost:8000/socket.io/socket.io.js" type="text/javascript"></script>
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8000');
socket.on('message', function(msg){
console.log(msg);
});
</script>
</body>
</html>
I have edited it just a little bit to run on my server. But the client doesn't send message to server. Can anybody help me? Sorry for my bad English.
I have found out that the client can't connect to server but I don't know why?
My computer is running xampp with apache server. Maybe it's problem?
Updated:
I have just set transports to xhr-polling and it connect success. Why doesn't it accept websocket?
you need to read more carefully the tutorials about socket.io
first of all to call some event, you need to emit the event name:
socket.emit('my other event', { my: 'data' });
thats mean, on your onclick in anchor need to call socket.emit ..., or to call some function like:
function call_my_event(name){
socket.emit(name,{my : 'data'});
}
I have found out my problem. It's about firewall or proxy or something else in my computer block websocket protocol. I tested that code on another computer and it works fine. So I have to re-install my system and websocket is available for me :D

node.js and socket.io

I have created a small server for communication using node.js and socket io
Server:
var express = require('/usr/local/lib/node_modules/express')
var io = require('/usr/local/lib/node_modules/socket.io');
var server = express.createServer();
server.listen(8888,'localhost');
io = io.listen(server);
io.of("namespace").on('connection', function(client){
client.emit("message",'connection successful');
client.on('message', function(m){
console.log("received message"+m);
client.broadcast(m);
});
});
Client:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
<script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
</head>
<body>
<p><a id='customAlert' href="#" onclick='sendMessage("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='sendMessage("customAlert2")'>publish customAl
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8888/namespace');
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('message', function(msg){
console.log(msg);
});
function sendMessage(m) {
console.log("sending message"+m);
socket.emit("message",m);
}
</script>
</body>
Communication does not happen, am I doing something wrong here?
If your server is listening on port 8888, you need the client to connect to the server on port 8888.
The following line in your client code:
var socket = io.connect('http://localhost/namespace');
Should read:
var socket = io.connect('http://localhost:8888/namespace');

node.js socket.io simple chat

I'm starting playing with node.js and as everybody, I want do a chat.
My idea is run node.js with socket.io in the port 9090, for example, and my client html in the port 8080. My html client will be served independent.
My server:
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
My client:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
$(document).ready(function () {
var socket = new io.Socket("localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (message) {
$('div#messages').append($('<p>'), message);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
socket.connect();
$('input').keydown(function (event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
</script>
</head>
<body>
<input type="text" style="width: 300px;" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
I'm running in ubuntu 11.04 with node.js v0.4.10.
The server works fine, but the client can't do connection, in the console.log on google Chrome I received this message:
XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1311465961485. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
The server.js is in a folder in /var/www/cliente/chat/public.
What's the problem?
Your client code is not actually being served from port 8080 as you want.
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function(req, res){
res.render('index.html', { title: 'Chat' });
});
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
This should fix your Access-Control-Allow-Origin errors. Execute node server.js and connect to http://localhost:8080. A couple additional notes:
Make sure you have installed socket.io 0.6.x since that's what you are including in your html file. 0.7.x is backwards incompatible.
With this configuration you'll be running socket.io on the same port you are serving your page from (as opposed to 9090).
When I updated my client to:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (msg) {
$('div#messages').append($('<p>'), msg);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
$(document).ready(function(){
$('#btn_send').click(function (event) {
socket.send($('#txt_msg').val());
$('#txt_msg').val('');
});
});
</script>
</head>
<body>
<input type="text" id="txt_msg" style="width: 300px;" /><input type="button" id="btn_send" value="send" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
Everything worked.
I was using a version 0.7 of the socket.io that was the problem: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
You cannot make AJAX requests to URLs that are not on the same hostname and port as the current page. It's a security restriction in all web browsers.

Problem with first program in socket.io

I am having some problems in executing my first socket.io program. Here is the code
var io=require('socket.io');
var http=require('http');
server =http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'text/html'});
res.write('welcome');
res.end();
});
server.listen(7777);
var socket = io.listen(server);
socket.on('connection', function (client) {
console.log('client connected');
client.emit('news', { hello: 'world' });
client.on('another', function (data) {
console.log(data);
});
});
And here is my client side code
<html>
<head>
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
<script type="text/javascript">
var socket = io.connect("http://localhost:7777");
socket.on('news',function(data) {
alert(data);
socket.emit('another',{my:'data'});
});
</script>
</head>
</html>
EDIT: Now, i get an error in my server terminal "info - client protocol unsupported"
what am i doing wrong here? Thanks
You are trying to import a javascript file from the socket io port instead of the web server port.
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
You need to give the correct src parameter. For newer version of socket io, this would be something like socket/socket.io.js.

Resources