Last active
December 22, 2020 19:46
-
-
Save jamilservicos/e7c09e3701a7ba5ff817096ef8426d94 to your computer and use it in GitHub Desktop.
socket.io multiples fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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