I'm using a Ubuntu server on DigitalOcean to host an Nginx web server and a Node app that runs a WebSocket server. When attempting to connect to the IP of the server, I get the following message in the console:
WebSocket connection to 'ws://<server's public IP>' failed: Error during WebSocket handshake: Unexpected response code: 200
All I did to set up Nginx was to follow this guide, which simply tells you to install Nginx and adjust the UFW firewall. I didn't set up server blocks in Step 4, and I haven't touched any other config files.
After that, I put my index.html
and client.js
files in the /var/www/html
directory to be served by Nginx.
index.html
is a very simple HTML page that runs client.js
. That JS file looks like this:
const ws = new WebSocket('ws://<public IP, same as above>:80');
ws.addEventListener('open', () => {
const json = { message: 'hello from client!' };
const jsonString = JSON.stringify(json);
ws.send(jsonString);
});
ws.addEventListener('message', event => {
const data = JSON.parse(event.data);
console.log(data);
});
The server side Node app is websocket.js
, and it looks like this:
const buffer = require('buffer');
const http = require('http').createServer();
const ws = require('ws');
const wsServer = new ws.Server({ server: http });
wsServer.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('received: ' + msg);
socket.send(Buffer.from('hello from the server!'));
});
const json = { message: 'hello from server!' };
const jsonString = JSON.stringify(json);
socket.send(Buffer.from(jsonString));
});
http.listen(8080, () => console.log('listening on 8080'));
This file was placed at /root
along with node_modules
, package.json
, and package-lock.json
. Serving it alongside the client side code at /var/www/html
didn't help. Of course, it was also running thanks to PM2, and I have also tried running without PM2 which made no difference.
Any help is appreciated, please let me know if there's any information I might have missed.