我一直在努力找出我不明白的地方:我在本地网络的计算机上运行了一个 NodeJS websocket 服务器。从那台计算机的浏览器中,我可以与 websocket 服务器通信。但是,在同一网络上的任何其他计算机上,我都会收到错误代码 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>