Reputation: 145
I'm new to node.js and working my way through examples of the 'smashing node.js' book.
In the websockets chapter I'm struggling to get this example to work. Forgive me it's a really simple error! I'm not sure the ws.onopen
event handler is working?
Code is below: (firstly server.js
file):
var express = require('express') , wsio = require('websocket.io');
var app = express.createServer().listen(3000);
var ws = wsio.attach(app);
app.use(express.static('public'));
ws.on('connection', function (socket) {
socket.on('message', function(msg) {
console.log(' \033[96mgot:\033[39m ' + msg);
socket.send('pong');
});
});
Secondly the script contents of the ./public/index.html
file:
var lastMessage;
window.onload = function () {
var ws = new WebSocket('ws://localhost');
ws.onopen = function () {
ping();
}
ws.onmessage = function(ev) {
console.log(' got: ' + ev.data);
document.getElementById('latency').innerHTML = new Date - lastMessage;
ping();
}
function ping() {
lastMessage =+ new Date;
ws.send('ping');
document.getElementById('latency').innerHTML = 'test';
};
};
I have installed the node modules using a package.json
file.
Upvotes: 1
Views: 1469
Reputation: 24922
In your index.html, you need to connect to port 3000 i.e. var ws = new WebSocket('ws://localhost:3000');
.
Upvotes: 1