私はnode.jsを初めて使用し、「smashingnode.js」の本の例を見ていきます。WebSocketの章では、この例を機能させるのに苦労しています。許してください、それは本当に単純なエラーです!ws.onopen
イベントハンドラーが機能しているかどうかわかりませんか?
コードは以下のとおりです:(最初にserver.js
ファイル):
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');
});
});
次に、./public/index.html
ファイルのスクリプトの内容:
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';
};
};
package.json
ファイルを使用してノードモジュールをインストールしました。