feat: allow renaming connection (#457)

* feat: allow renaming connection
This commit is contained in:
Carlos Valente
2023-07-21 20:15:54 +02:00
committed by GitHub
parent 6ef6b0fdcd
commit db1155ce1a
8 changed files with 180 additions and 21 deletions
+38 -13
View File
@@ -45,9 +45,9 @@ export class SocketServer implements IAdapter {
this.wss = new WebSocketServer({ path: '/ws', server });
this.wss.on('connection', (ws) => {
const clientId = getRandomName();
let clientId = getRandomName();
this.clientIds.add(clientId);
logger.info('RX', `${this.wss.clients.size} Connections with new: ${clientId}`);
logger.info('CLIENT', `${this.wss.clients.size} Connections with new: ${clientId}`);
// send store payload on connect
ws.send(
@@ -57,10 +57,17 @@ export class SocketServer implements IAdapter {
}),
);
ws.send(
JSON.stringify({
type: 'client-name',
payload: clientId,
}),
);
ws.on('error', console.error);
ws.on('close', () => {
logger.info('RX', `${this.wss.clients.size} Connections with disconnected: ${clientId}`);
logger.info('CLIENT', `${this.wss.clients.size} Connections with disconnected: ${clientId}`);
this.clientIds.delete(clientId);
});
@@ -69,20 +76,37 @@ export class SocketServer implements IAdapter {
ws.close();
}
// TODO: protocol specific stuff should be handled here
// eg: rename-client
// socket.on('rename-client', (newName) => {
// if (newName) {
// const previousName = this._clientNames[socket.id];
// this._clientNames[socket.id] = newName;
// this.info('CLIENT', `Client ${previousName} renamed to ${newName}`);
// }
// });
try {
const message = JSON.parse(data);
const { type, payload } = message;
if (type === 'get-client-name') {
ws.send(
JSON.stringify({
type: 'client-name',
payload: clientId,
}),
);
return;
}
if (type === 'set-client-name') {
if (payload) {
const previousName = clientId;
clientId = payload;
this.clientIds.delete(previousName);
this.clientIds.add(clientId);
logger.info('CLIENT', `Client ${previousName} renamed to ${clientId}`);
}
ws.send(
JSON.stringify({
type: 'client-name',
payload: clientId,
}),
);
return;
}
if (type === 'hello') {
ws.send('hi');
return;
@@ -95,6 +119,7 @@ export class SocketServer implements IAdapter {
return;
}
// Protocol specific stuff handled above
try {
const reply = dispatchFromAdapter(type, payload, 'ws');
if (reply) {