I'm currently trying to write a websocket connector between the server and one exclusive client for real-time information exchange between the two using ws.js. I would like that the server automatically asks the client for authentication what i have looks like this:
const ws = require("ws");
const pass = "1234"
class WebsocketHandler {
constructor(port = 8080) {
this.server = new ws.Server();
this.server.on("connection", this.startHandleConnection.bind(this));
}
startHandleConnection(wsc) {
this.wsc = wsc;
//Authorize the client with a password before accepting the connection
wsc.on("message", this.handleMessage.bind(this));
wsc.send("Authorize"); // The client-side is expected to respond with the password
}
handleMessage(message) {
if(!this.authorized && message !== pass) {
delete this.wsc;
} else {
//do stuff
}
}
}
Is there a more elegant approach to this?