Pardon me but I am new to JS and node altogether. Trying to stitch things together and learn.
I am trying to implement a wss server that listens to say port 8010. I am using nginx to reverse proxy the requests on port 8020 for the websocket to port 8010 .
I tried using the example script ssl.js from the repository and made basic changes as warranted (path to certificate, keys and ws library etc). The script executes without error but upon firing a request from the browser (for the html page that invokes the websocket client code) does not result in a successful connection.
Moreover wscat -c wss://localhost:8010 also throws a error:self signed certificate because of which I'm unable to ascertain if the issue is with the server code, my nginx setup or elsewhere.
If it helps, attaching the relevant scripts and configuration
nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server localhost:8010;
}
server {
listen 8020;
ssl on;
include /etc/nginx/snippets/ssl-params.conf;
include /etc/nginx/snippets/self-signed.conf;
location / {
proxy_pass http://localhost:8010;
proxy_http_version 1.1;
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
client side java script
window.onload = function() {
//alert('sadsads');
//const WebSocket = require('/usr/local/lib/ws');
//alert('sdfsdfdsfdhgdhgfhfg');
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
alert('sdfsdfdsfdhgdhgfhfg');
// Create a new WebSocket.
var socket = new WebSocket('wss://localhost:8020');
// Handle any errors that occur.
socket.onerror = function(error) {
socketStatus.innerHTML = 'WebSocket Error: ' + error;
};
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
socketStatus.className = 'open';
};
// Handle messages sent by the server.socketStat
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
message + '</li>';
};
// Show a disconnected message when the WebSocket is closed.
socket.onclose = function(event) {
socketStatus.innerHTML = 'Disconnected from WebSocket.';
socketStatus.className = 'closed';
};
// Send a message when the form is submitted.
form.onsubmit = function(e) {
e.preventDefault();
socketStatus.innerHTML = 'PRESSED from WebSocket.';
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
};
node js server script (from the examples folder)
(function () {
'use strict';
var fs = require('fs');
// you'll probably load configuration from config
var cfg = {
ssl: true,
port: 8010,
ssl_key: '/etc/ssl/private/nginx-selfsigned.key',
ssl_cert: '/etc/ssl/certs/nginx-selfsigned.crt'
};
var httpServ = (cfg.ssl) ? require('https') : require('http');
var WebSocketServer = require('ws').Server;
var app = null;
// dummy request processing
var processRequest = function (req, res) {
res.writeHead(200);
res.end('All glory to WebSockets!\n');
};
if (cfg.ssl) {
app = httpServ.createServer({
// providing server with SSL key/cert
key: fs.readFileSync(cfg.ssl_key),
cert: fs.readFileSync(cfg.ssl_cert)
}, processRequest).listen(cfg.port);
} else {
app = httpServ.createServer(processRequest).listen(cfg.port);
}
// passing or reference to web server so WS would knew port and SSL capabilities
var wss = new WebSocketServer({ server: app });
wss.on('connection', function (wsConnect) {
wsConnect.on('message', function (message) {
console.log(message);
});
});
}());
Moreover
wscat -c wss://localhost:8010also throws aerror:self signed certificate
If you are using the example in this repo you have to set the rejectUnauthorized to false on the client because the certificate is self signed and is rejected by default.
With this setup where both the proxy and the WebSocket server are on the same machine, you can probably skip the SSL config for the WebSocket server. You can use NGINX as your SSL terminator.
if you are using the example in this repo you have to set the
rejectUnauthorizedtofalseon the client because the certificate is self signed and is rejected by default.
Cant seem to locate the setting in the client script. Do i need to amend the required settings in the path_to_ws/lib/WebSocket.js file? Thanks for the patience.
@sherikapotein You can't do this in the browser but if you are using the Node.js client you can pass an options object to the constructor:
const ws = new WebSocket('wss://localhost:8010', {
rejectUnauthorized: false
});
Use the proxy port to see if your NGINX config works as expected.
@sherikapotein did you make any progress? Can I close this?
Still stuck, but i guess u have answered my question .That calls for a closure. Need to hunt for issues in in other configs.
Thanks!
Ok I'm going to close this. I've updated the SSL example if that can be of help.
@lpinca How can I change port in your example?
I figured out.
server.listen(PORT_NUM, function listening () {...}
Most helpful comment
@sherikapotein You can't do this in the browser but if you are using the Node.js client you can pass an options object to the constructor:
Use the proxy port to see if your NGINX config works as expected.