Skip to content

Instantly share code, notes, and snippets.

@jamilservicos
Last active December 22, 2020 19:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamilservicos/e7c09e3701a7ba5ff817096ef8426d94 to your computer and use it in GitHub Desktop.
Save jamilservicos/e7c09e3701a7ba5ff817096ef8426d94 to your computer and use it in GitHub Desktop.
socket.io multiples fix
'use strict';
var reconnection = true,
reconnectionDelay = 5000,
reconnectionTry = 0;
function initClient() {
connectClient();
}
function connectClient() {
var socket = "";
socket = io.connect('http://localhost:3000');
socket.on('connect', function (e) {
routesClient(socket);
});
socket.on("connect_error", function(e){
reconnectionTry++;
console.log("Reconnection attempt #"+reconnectionTry);
});
return false;
}
function routesClient(socket){
console.log('connected');
socket.on('test', function (e) {
console.log(e);
socket.emit("test", "pong");
});
socket.on('disconnect', function () {
socket.disconnect();
console.log("client disconnected");
if(reconnection === true) {
setTimeout(function () {
console.log("client trying reconnect");
connectClient();
}, reconnectionDelay);
}
});
return false;
}
window.onload = function () {
initClient();
};
var io = require('socket.io').listen(server);
var clients = {};
io.sockets.on('connection', function (socket) {
clients[socket.id] = socket;
console.log('a user connected: ' + socket.id);
socket.emit("test", "ping");
socket.on('test', function (e) {
console.log(e);
});
socket.on("disconnect",function(data){
delete clients[socket.id];
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment