I'm trying to create a socket that joins a specific room when it is connected, where the room I want it to join is set as a custom property of the client-side socket.
The idea here being that the server socket reads that custom room parameter and joins the socket to that room.
However, the server is not getting the room parameter I am setting on the client socket (i.e., no custom data is being stored in the socket the server receives on connection), and the socket doesn't work.
So on the client side I have something like
interface CustomSocket extends Socket {
socket_room:string,
};
class client_socket {
socket:CustomSocket;
constructor(socket_room:string){
this.socket = <CustomSocket>io("/custom_namespace");
this.socket.socket_room = socket_room;
this.socket.on(`custom_namespace:${socket_room}`,(arg) => {
console.log(arg);
});
};
};
And then on the server side I have something like
const io = new Server(server); // Express Server
const custom_namespace = io.of("/custom_namespace");
custom_namespace.on("connection",(socket) => {
console.log(socket.data.socket_room); // undefined
socket.join(socket.data.socket_room); // Joins undefined room
});
And then the socket doesn't work properly (receives no emissions from the server).
On the other hand, if I don't assign the client socket to a custom namespace, i.e. declare the client socket as
this.socket = <CustomSocket>io(); // <- Assigned to global namespace
(vs. this.socket = <CustomSocket>io("/custom_namespace");), the server-side socket gets the data stored in the socket_room field:
const io = new Server(server); // Express Server
io.on("connection",(socket) => {
console.log(socket.data.socket_room); // Correctly prints value of socket_room set in client_socket constructor
});
I don't understand how to solve this problem, or why it even exists?
Note that I strongly prefer to store the socket_room parameter in the client socket, instead of using an emission to tell the server what room that socket should join.