Skip to content

Commit

Permalink
shouldHandle
Browse files Browse the repository at this point in the history
  • Loading branch information
dimdenGD committed Oct 10, 2024
1 parent a0b52ef commit a09dbf2
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ Below is the list of supported features and their compatibility:
- ✅ server.address()
- ✅ server.clients
- ✅ server.close(callback)
- ✅ server.shouldHandle(request)
- ❌ server.handleUpgrade(request, socket, head, callback) - see examples above for alternatives
- ❌ server.shouldHandle(request)

### Client

Expand Down
8 changes: 8 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ module.exports = class WebSocketServer extends EventEmitter {
msg.finished = true;
});

if(!this.shouldHandle(msg)) {
return res.writeStatus("400 Bad Request").end();
}

if(this.options.verifyClient) {
if(this.options.verifyClient.length === 1) {
const result = this.options.verifyClient({
Expand Down Expand Up @@ -223,6 +227,10 @@ module.exports = class WebSocketServer extends EventEmitter {
});
}

shouldHandle(req) {
return true;
}

address() {
const host = this.options.host ?? '::';
return { address: host, family: host.includes(':') ? 'IPv6' : 'IPv4', port: this.port };
Expand Down
32 changes: 32 additions & 0 deletions tests/tests/server/shouldHandle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// must support server.shouldHandle

const ws = require("ws");

const wss = new ws.WebSocketServer({ port: 8080 }, cb);

wss.shouldHandle = (req) => {
return false;
}

wss.on("connection", (ws, req) => {
console.log('connected');
});


function cb() {
const c = new ws.WebSocket("ws://localhost:8080");
c.on("open", () => {
console.log("Connected to server");
c.send("Hello from client");
c.close();
});
c.on("close", () => {
setTimeout(() => {
console.log('closed');
process.exit(0);
}, 100);
});
c.on("error", (err) => {
console.log(err.message);
});
}

0 comments on commit a09dbf2

Please sign in to comment.