I am making a web app that shows the user when the server is reachable so they can post data. Currently it works with the code I am using but I am having an issue when another user connects / disconnects it directly affects another client that is connected.
NodeJS code:
io.on('connection', function(socket) {
console.log('Connected');
io.emit('Connect');
socket.on('disconnect', function () {
console.log('Connection Lost');
io.emit('disconnect');
});
});
HTML code:
socket.on('disconnect', function(){
$('#connection').html('disconnected');
document.getElementById(id = 'save_button').style.display = "none"
document.getElementById(id = 'not_save_button').style.display = "block"
});
socket.on('Connect',function() {
$('#connection').html('connected');
document.getElementById(id = 'save_button').style.display = "block"
document.getElementById(id = 'not_save_button').style.display = "none"
});
So basically I am trying to make each page only listen to the server. It currently works perfectly with just one client but when you add anything else to the system it can't function.
I have tried socket ID but these get updated when the server reconnects so I couldn't find a way to make these work.
The Server.emit
function emits the message to all clients. To send to a specific client, use the Socket.emit
method of the relevant socket. In your case:
io.on('connection', function(socket) {
console.log('Connected');
socket.emit('Connect');
socket.on('disconnect', function () {
console.log('Connection Lost');
});
io.on('connection', function(socket) {
console.log('Connected');
socket.emit('Connect');
});
io.on('disconnect', function () {
console.log('Connection Lost');
socket.emit('disconnect');
});
Using Amit's answer I managed to find a solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.