'Socket.io: getting information from all other clients who are already in a room
I am working with socket.io and I am trying to get some information from all of the other clients who are already in the room when a new client joins but I am a bit lost on what to do. On the client side, each socket client has some personal information like name, userId, and color associated with it, looking like this:
import { io, Socket } from 'socket.io-client';
class SocketClient {
socket: Socket;
userId: string;
name: string;
color: string;
roomId: number;
}
Upon joining a room, I would like to know this information about all other clients, but I am a bit confused and I feel like the method I am working with so far is overly complicated for no reason. Here is what I'm doing
CLIENT SIDE:
type UserId = string;
type UserInfo = {color: string, name: string}
type UserSelectionMap_t = Map<UserId, UserInfo>;
public async joinRoom() {
// join the room with this call
this.socket.emit(
'workbook:subscribe',
roomId: this.room,
);
// Now I want the information from the other clients in the room
this.setUserMap(await this.getOtherUsers());
}
async getSelections(): Promise<UserSelectionMap_t> {
return new Promise((resolve, _reject) => {
this.socket.emit(
'listUsers',
roomId: this.roomId,
function (users: UserInformationMap_t) {
resolve(users);
},
);
});
}
Now on the server side I think I need something like this which calls back to the client
// this function gets called on a 'listUsers' message:
function handleListUsers(roomId: number): UserSelectionMap_t {
let idToInfoMap = new Map<UserId, UserInfo>();
// - call into each client and get their userId and workbookId?
// - Do I need another emit to client here
// triggering a callback which would return the users information?
return idToInfoMap;
}
Is this the best way to be doing this? It seems like a lot of client-server chit chat just to get some information. And if this is the best way, if each client emits their information, how do I organize the returns from multiple clients into a UserSelectionMap_t?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
