Reputation: 845
I've been struggling to figure out what I don't understand: I have a NodeJS websocket server running on a computer on my local network. From that computer's browser, I can communicate with the websocket server. However, from any other computer on the same network, I get a forced closeEvent with error code 1006.
Attached are both server and client files. The client file is also being served from the same place. Any help in broadening my understanding here would be most greatly appreciated.
Thanks!
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);
});
});
<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>
Upvotes: 1
Views: 7351
Reputation: 14881
Maybe it's just a typo in the code, but did you change the address in ws://127.0.0.1:8080
when attempting from the other computer ?
127.0.0.1
always refer to the local host, which is not what you want here.
You should put the local address instead (something like 192.168.0.5
), or better: new WebSocket('/');
, which will connect to the same host and port as the page.
Upvotes: 4