I have a simple chat app, using react-native, nodejs, and socket.io, they all works very well.
But there is some cases which doesn't work as expected.
My Expectation:
I want for above cases, it should work as well.
const onlineusers = {};
io.on('connection', function(socket) {
socket.on('online', user => {
onlineusers[user] = cs.id;
io.emit('online', onlineusers);
});
socket.on('message', data => {
socket.broadcast.to(data.userid).emit('message', data);
});
});
this.socket = io('domainname.com:5412', { transports: ['websocket'] });
if(this.socket.connected) {
this.socket.emit("online", this.myuserid);
this.socket.on('online', users => {
console.log('online users', users);
});
this.socket.on('connect', ()=> {
this.socket.emit("online", this.myuserid);
});
this.socket.on('message', message => {
console.log(message);
});
this.socket.on('disconnect', reason => {
if(reason==='io server disconnect') this.socket.connect();
});
}
sendMessage = message => {
this.socket.emit('message', message);
}
it should auto reconnect.. you dont need this
if(reason==='io server disconnect') this.socket.connect();
and please remove this if(this.socket.connected) {
let the socket io do its job..
and please remove this
if(this.socket.connected) {
It鈥檚 needed before calling socket.emit(...)
, though not for adding the event handlers. All the examples on the socket.io website do it this way, and I鈥檝e experienced myself that if you don鈥檛 do it, socket.io will open multiple concurrent http connections when not connected, sending the same message multiple times when finally connecting.
its redundant connect wont fire if its not connected #if(this.socket.connected)
The connect event won't fire, correct, but it's not redundant as everything sent via socket.emit(...)
might get sent multiple times, as I described above. I observed this in practice.
your doing something wrong.. or your using outdated ones .. yes socket io will fire multi times because its auto retrying ... but it wont send multi times if you have slow net or suddenly gets disconnected.. socket io handles it very well. its an event.. an event should be called = * emit ..