1

I'm writing a pretty simple app (for now) and I need to log each connection and disconnection inside a div. Currently I can log every connection and disconnection on my console with the code I have but do to my limited knowledge of socket.io, I can't figure out how to log them in a div on my index.html file i.e. I need the server.js to emit(?) the connections and disconnections and append them to the div instead of just logging them on my console. I included my server.js file and my html file (which contains the client sided script).

My server.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);




app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    ID = socket.id;
    console.log('client id - ' + socket.id + ' connected.');
    socket.on('disconnect', function() {
        console.log('client id - ' + socket.id + ' disconnected.')})

})



server.listen(80, '95.211.186.223', function () {
    console.log("Listening on 80")
}); 

My index.html

<!doctype html>  
<html lang="en">  
<head></head>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>    
    <script>  
        var socket = io.connect('http://95.211.186.223:80');
        socket.on('connect', function(data) {
            console.log('ID: ' + socket.id)
         });
    </script>   

    <div id="log"></div>
</body>
</html>  
Marko Nikolov
  • 655
  • 2
  • 8
  • 15

1 Answers1

0

There are many ways to implement that. Just one of them:

On server:

io.on('connection', function (socket) {
    ID = socket.id;
    console.log('client id - ' + socket.id + ' connected.');
    io.sockets.emit('connect_event', data);     
})

io.on('disconnect', function() {
    ID = socket.id;
    console.log('client id - ' + socket.id + ' disconnected.');
    io.sockets.emit('disconnect_event', data);
}

If you want to know how to emit a message to everyone see the relevant question.

On client:

function addText(eventType) {
    var p = document.createElement('p');
    p.innerHTML = 'ID: ' + socket.id  + ' ' + eventType;
    document.body.appendChild(p);
}
socket.on('connect_event', function(data) {
    addText('connected')
});
socket.on('disconnect_event', function(data) {
    addText('disconnected')
});
kurumkan
  • 2,635
  • 3
  • 31
  • 55
  • Maybe I wasn't descriptive enough. This will give the socket.id of each connection and print it out to them. I need all new connections and disconnections to be logged. Not just the one on the page. I presume that the server.js will have to emit that data to the index file so that every new connection appends to the div instead of just the one. – Marko Nikolov Sep 22 '17 at 12:10
  • updated the answer. Hope I got your question correctly. – kurumkan Sep 22 '17 at 12:44
  • Yes. Thank you very much. – Marko Nikolov Sep 25 '17 at 07:20