Ich verwende Socket.Io 1.7.3 auf Angular 2, die an ExpressJS Server anschließen. Ich kann das Paket nicht an die spezifische Socket-ID senden, Ereignis sie sind tatsächlich übereinstimmen.Socket.io Senden an bestimmte socketId funktioniert nicht
Server-Implementierung:
socket.on('subscribeNotification', function(data){
// Get new notification by user_id here ....
console.log('Got notification request');
console.log('Your Id is: '+socket.id);
socket.broadcast.to(socket.id).emit('sendNotificationsToUser', {
text: 'hello',
id: socket.id
});
socket.emit('claimId', {
id: socket.id
});
});
Und auf Angular 2 Umsetzung:
subscribeNotificationEvent(userId: string) {
let socket = this.socket;
let data = {
user_id: userId
};
// Emit socket
socket.emit('subscribeNotification', data);
}
listenToNotification() {
let socket = this.socket;
socket.on('sendNotificationsToUser', function (data) {
console.log('I hear it !');
});
socket.on('claimId', (data) => {
console.log('My id is: ' + data.id);
})
}
Logging Ergebnis
Server:
Got notification request
Your Id is: bSCHMUL2bJJQCXkxAAAC
Auftraggeber:
My id is: bSCHMUL2bJJQCXkxAAAC
Der Kunde nicht sendNotificationsToUser
Ereignis empfängt, so dass es nicht über die Linie 'I hear it !'
abmelden kann.
Ich habe auch auf Sending message to specific client in Socket IO verwiesen, aber es funktioniert nicht.
Warum verwenden Sie 'socket.broadcast.to' (dass ich nicht se überall dokumentiert) statt' socket.send'? – rpadovani
@rpadovani Ich bekomme es hier https://socket.io/docs/server-api/ und auch aus dem Post, den ich angehängt habe. Das Beispiel in ihrem offiziellen Dokument: 'client.broadcast.to (id) .emit ('meine Nachricht', msg);' – ThangLeQuoc