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');
Related
I have written code for socket from :source
My code looks like this.
var port = 8081;
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(port);
io.on('connection', function (socket) {
console.log("New user connected.");
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log("server listening on: " + port);
But when I am testing it on here (ws://localhost:8081). I am getting
ERROR: undefined
DISCONNECTED
In console I am getting error:
WebSocket connection to 'ws://localhost:8081/?encoding=text' failed: Connection closed before receiving a handshake response
You need to use the socket.io client library, either getting it, from here, or referencing their CDN from your page like this:
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
Additionally, whenever you start a socket.io server, socket.io will be served from http://<your-server-address>/socket.io/socket.io.js. You should be able to test your server using this simple page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://localhost:8081/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8081/');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
</body>
</html>
You can read more about why you can't connect from the websocket.org site on this github issue.
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)});
});
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>
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
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.