losing reference to the socket in socket.io
I am having a typescript class on the server that is handling my socket.io communications that looks like below. basically it works, but ofc the server just saves the latest socket reference. (the person who last connected to the server, because the variable gets overwritten each time someone connects).
class ChatService {
private server;
private app;
private io;
private socket;
constructor(app, server) {
this.app = app;
this.server = server;
this.io = require('socket.io').listen(this.server);
this.io.set('log level', 1);
this.io.sockets.on('connection', (socket) => {
console.log('a user connected');
socket.join('test');
console.log(this.io.sockets.clients('test').length + ' - ' + socket.id);
this.socket = socket;
socket.on('message', (data) => this.onMessage());
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
}
public onMessage() {
this.socket.broadcast.to('test').emit('message', {
message: 'test message'
});
}
}
export = ChatService;
Do you have any good practise how I can have the right reference ( so that i can call socket.broadcast.to('test').emit()
). Maybe there is a way, that the client send his socket element, so that i have it on the server?
socket.on('message', (data) => this.onMessage());
Change it by this :
socket.on('message', (data) => this.onMessage(socket,data));
Then you have everything you need for broadcast and resend data.
public onMessage(socket,data) {
socket.broadcast.to('test').emit('message', {
message: 'test message'
});
}
链接地址: http://www.djcxy.com/p/94598.html
上一篇: 哪个WebSocket库在Android应用程序中使用?
下一篇: 在socket.io中丢失对套接字的引用