如果不是localhost,则无法使浏览器连接到nodejs WS服务器

时间:2013-03-09 07:34:30

标签: node.js websocket

我一直在努力弄清楚我不理解的东西:我在本地网络上的计算机上运行了一个NodeJS websocket服务器。从该计算机的浏览器,我可以与websocket服务器进行通信。但是,从同一网络上的任何其他计算机,我得到一个强制closeEvent,错误代码为1006。

附件是服务器和客户端文件。客户端文件也在同一个地方提供。任何有助于扩大我的理解的人都会非常感激。

谢谢!


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>

1 个答案:

答案 0 :(得分:4)

也许这只是代码中的拼写错误,但是当您从另一台计算机上尝试时,您是否更改了ws://127.0.0.1:8080中的地址?

127.0.0.1总是引用本地主机,这不是你想要的。

您应该改为使用本地地址(类似192.168.0.5)或更好:new WebSocket('/');,它将连接到与页面相同的主机和端口。