c6477698c0
* Make 'ws' (collaboration) and socket.io work on same server port
40 lines
965 B
TypeScript
40 lines
965 B
TypeScript
import { WebSocketServer } from 'ws';
|
|
|
|
export class CollabWsAdapter {
|
|
private readonly wss: WebSocketServer;
|
|
|
|
constructor() {
|
|
this.wss = new WebSocketServer({ noServer: true });
|
|
}
|
|
|
|
handleUpgrade(path: string, httpServer) {
|
|
httpServer.on('upgrade', (request, socket, head) => {
|
|
try {
|
|
const baseUrl = 'ws://' + request.headers.host + '/';
|
|
const pathname = new URL(request.url, baseUrl).pathname;
|
|
|
|
if (pathname === path) {
|
|
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
this.wss.emit('connection', ws, request);
|
|
});
|
|
} else if (pathname === '/socket.io/') {
|
|
return;
|
|
} else {
|
|
socket.destroy();
|
|
}
|
|
} catch (err) {
|
|
socket.end('HTTP/1.1 400\r\n' + err.message);
|
|
}
|
|
});
|
|
|
|
return this.wss;
|
|
}
|
|
|
|
public close() {
|
|
this.wss.clients.forEach((client) => {
|
|
client.terminate();
|
|
});
|
|
this.wss.close();
|
|
}
|
|
}
|