1

私は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ファイルを使用してノードモジュールをインストールしました。

4

1 に答える 1

1

index.htmlで、ポート3000に接続する必要がありますvar ws = new WebSocket('ws://localhost:3000');

于 2013-02-21T11:03:11.497 に答える