Carliedu
Carliedu

Reputation: 71

How to write a code to simulate the same as echo server from Websocket.org

i need to create a server based on the same logic as the echo server on websocket.org. The difference is that the server will not echo exactly what the user typed, but will return a response that varies with the received string.

I've been looking for more than a week and I only found n examples that only explain the client, some of which include an example of a server that does NOT answer wss:// calls. Everything I found responds only to calls http://192.168.1.1:3000 or https://192.168.1.1:3000, but when I use wss: //192.168.1.1:3000, Firefox says, it was unable to establish a connection with the wss server: //192.168.1.1:3000/. The client works when I call wss: //echo.websocket.org/.

Where do I find the code for an echo server that responds to wss?

Above I list the code I found on github. The nodejs server code I'm trying is:

const http = require('http');
const ws = require('ws');

const wss = new ws.Server({noServer: true});

console.log("Script has started");

if (!module.parent) {
    console.log("Listening on port 3000");
    http.createServer(accept).listen(3000);
} else {
    exports.accept = accept;
}


function accept(req, res) {
    console.log("accept event started");
    // all incoming requests must be websockets
    if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
        console.log("This is no websocket!!! Return");
            res.end();
            return;
    }

    // can be Connection: keep-alive, Upgrade
    if (!req.headers.connection.match(/\bupgrade\b/i)) {
        res.end();
        return;
    }
    console.log("Handle upgrade");
    wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}

function onConnect(ws) {
    console.log("onConnect event started");
    ws.on('message', function (message) {
        let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
        console.log("Send Hello");
        ws.send(`Hello from server, ${name}!`);

        setTimeout(() => ws.close(1000, "Bye!"), 5000);
    });
}

This code, responds "This is no websocket!!! Return" if I call the server with http://192.168.1.1: 3000/

Thank you in advance.

Upvotes: 1

Views: 2544

Answers (1)

Carliedu
Carliedu

Reputation: 71

After a while I found the solution:

//  Basic Websocket (ws) echo server
const WebSocket = require('ws');

const ws_server = new WebSocket.Server({ port: 81 });

ws_server.on('connection', function connection(ws) {
    console.log("A client connected");
    ws.on('message', function incoming(message) {
        ws.send('Hi, you sent me ' + message);
    });
});

This works for my tests.

Upvotes: 4

Related Questions