I've been messing around with node.js/socket.io on a VPS, trying to do a basic send & receive. Seems to authorise okay and everything and I get this on the VPS: websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
although I only see anything on the client when they've disconnected. After they're disconnected I get the word "world" shown. Am I doing something wrong, as shouldn't I see that word while they're still connected? Thanks for the help.
I'm using this code:
Client:
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<script src="http://IP-ADDRESS/socket.io/socket.io.js"></script>
<script>
var socket = io
.connect('http://IP-ADDRESS:80');
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
socket.emit('my other event', { my: 'data' });
});
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
msgArea.innerHTML = msg.hello;
}
else {
msgArea.innerHTML = msg;
}
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
Server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
A year later I'm now using pure websockets. I got socket.io working eventually (can't remember what the problem here was) but it didn't work how I wanted. Websockets work great however.