Search code examples
node.jswebsocketbrowserhttpsresponse

Simple HTTP(S) Response on WebSocket (WSS) Server


I am running a websocket (wss) server (with certificate) on port 443. For this i am using the "https" and "ws" module in nodejs (simplified):

require(__dirname + './config.js');
const https = require('https');
const WebSocketServer = require('ws');
const server = new https.createServer({
    key: fs.readFileSync('./privkey.pem'),
    cert: fs.readFileSync('./fullchain.pem')
});
const wss = new WebSocketServer.Server({server: server});
wss.on("connection", function(socket){
    const c_inst = new require('./client.js');
    const thisClient = new c_inst();
    thisClient.socket = socket;
    thisClient.initiate();
    socket.on('error', thisClient.error);
    socket.on('close', thisClient.end);
    socket.on('message', thisClient.data);
});
server.listen(config.port, config.ip);

The wss communication works perfect! But if i open the wss url via https:// in the browser i get a timeout error (Error code 524) because there is no response for a "normal" (https/get) request.

How can i implement a response for this case in my wss server? I just want to send a response with a simple text or html like "This is a websocket server" or do a redirect to another url if someone connects to the wss socket via browser/https.

Thanks!


Solution

  • See the documentation for HTTPS server on node. https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener

    You need to add request listener when you create a server.

    const server = new https.createServer(
        {
            key: fs.readFileSync('./privkey.pem'),
            cert: fs.readFileSync('./fullchain.pem')
        },
        (req, res) => {
            res.writeHead(200);
            res.end('This is a websocket server\n');
            // do redirects or whanever you want
        }
    );