1

理解できないことを理解するのに苦労しています。ローカルネットワーク上のコンピューターで NodeJS Websocket サーバーを実行しています。そのコンピューターのブラウザーから、websocket サーバーと通信できます。ただし、同じネットワーク上の他のコンピューターからは、エラー コード 1006 の強制 closeEvent が発生します。

サーバー ファイルとクライアント ファイルの両方が添付されています。クライアントファイルも同じ場所から提供されています。ここで私の理解を広げるための助けがあれば、大歓迎です。

ありがとう!


ws_server.js

var fs = require('fs');
var path = require('path');
var httpServer = require('http').createServer(
    function(request, response) {
        if(request.url != ''){//request.url is the file being requested by the client
            var filePath = '.' + request.url;
            if (filePath == './'){filePath = './ws_client.html';} // Serve index.html if ./ was requested
            var filename = path.basename(filePath);
            var extname = path.extname(filePath);
            var contentType = 'text/html';
            fs.readFile(filePath, function(error, content) {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            });
        }
    }
).listen(8080);

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({server:httpServer});
wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
        ws.send("You said: "+ message);
    });
});

ws_client.html

<html>
<head>
    <title>WS</title>
    <script>
        var connection = new WebSocket('ws://127.0.0.1:8080');
        connection.onopen = function () {connection.send("The time is " + new Date().getTime());};
        connection.onmessage = function (e) {document.getElementById("capture").innerHTML = e.data;};
        connection.onclose = function(event) {console.log(event);};
    </script>
</head>
<body>

<textarea id="capture"></textarea>

</body>
</html>
4

1 に答える 1

4

コードのタイプミスかもしれませんがws://127.0.0.1:8080、他のコンピュータから試行するときにアドレスを変更しましたか?

127.0.0.1常にローカルホストを参照してください。これは、ここで必要なものではありません。

代わりにローカル アドレス ( のようなもの) を配置するか、ページと同じホストとポートに接続する192.168.0.5より良い:を配置する必要があります。new WebSocket('/');

于 2013-03-09T08:50:26.223 に答える