'socket.io doesn't send message back to socket
i'm working on an app which communicate with server via socket.io, users in my app have unique ids which i want to use on my server so i made a small class which contains fields with these unique ids and a socket
import {Socket} from 'socket.io'
export interface VKClient{
vkid: string,
socket: Socket
}
export class VKClients{
clients: VKClient[] = []
addClient(client: VKClient){
this.clients.push(client)
}
sendToClient(id: string, message: string, data?: any){
this.clients.find(x => x.vkid === id)?.socket.emit(message)
}
}
so in index.ts i have structure
const io = new Server(5000, {
cors: {
origin: '*'
}
})
const clients = new VKClients()
io.on('connection', (client) => onConnect(client, clients))
and onConnect handler looks like
const onConnect = (client: Socket, clients: VKClients) => {
client.on('handshake', (data: {uid: string, salt: string}) => {
const newClient: VKClient = {vkid: data.uid, socket: client}
clients.addClient(newClient)
clients.sendToClient(data.uid, 'handshake')
})
client.on('getThemes', async (callback) => callback(await getThemes()))
}
the problem is when user on a client side sends handshake message nothing happens, the server receives this message, the data is normal, it has id and hash, the socket is added to my class, i can find him there via custom id, but i can't send message using sendToClient method, broadcast from socket.io and foreach works fine, and if i console.log structure inside sendToClient method it will log true
p.s. ids which are operated by socket.io in the class and in the onConnect handler are identical
Solution 1:[1]
it seems like there is an issue in my logic of storing clients because when i replace this...find(x => x.vkid === id)... to forEach(x => {if(x.vkid === id)...} it works as expected
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xoma_star |
