如果不是localhost,不能让浏览器连接到nodejs WS服务器

我一直在努力弄清楚我不明白的东西:我的本地networking上有一台运行在计算机上的NodeJS websocket服务器。 从那台电脑的浏览器,我可以与websocket服务器通信。 但是,从同一networking上的任何其他计算机,我得到一个错误代码为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> 

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

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

你应该把本地地址,而不是(如192.168.0.5 ),或更好的: new WebSocket('/'); ,它将连接到与页面相同的主机和端口。