Saturday 18 March 2017

Emit socket when user connected to chat

I am trying to update the number of users connected to the chat everytime a user connects, but is not working. It works for disconnect but not for connection.
Here is the server

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

var app = express();
var server = http.createServer( app );

var io = socket.listen( server );
server.listen( 8080 );

connections = [];

io.sockets.on( 'connection', function( client ) {
        connections.push(client);
        console.log( "---CONNECT--- INFO --> New user connected! >>>>> USERS ONLINE: %s", connections.length);

        client.on('connection', function(data){
                io.sockets.emit('connect', {users:connections.length});
        });

        client.on('disconnect', function(data){
                connections.splice(connections.indexOf(client),1);
                console.log("---DISCONNECT--- INFO --> User disconnected >>>>> USERS LEFT: %s", connections.length);

                io.sockets.emit('disconnect', {users:connections.length});
        });

        client.on( 'message', function( data ) {
                console.log( 'Message received from: ' + data.id);

                io.sockets.emit( 'message', {id:data.id, name: data.name, avatar: data.avatar, message: data.message } );
        });
});

If I do like this the disconnect stops working and the server stops working properly. If I emit outside the client.on which would be inside the io.sockets.on('connection') the server will crash.
On the clients I have this:

var socket = io.connect( 'http://localhost:8080' );

socket.on('connect', function(data){
    $("#usersOnline").html(data.users);
});
socket.on('disconnect', function(data){
    $("#usersOnline").html(data.users);
});


via Daniel

No comments:

Post a Comment