tony3243 tony3243 - 1 month ago 7
HTML Question

Socket IO doesn't send array

I am trying to show all usernames online with socket.io:
Here is the server side code:

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

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var send="dsf";
var usernames=[];
var users=0;
io.on('connection', function(socket){
users++;
console.log(users);
io.emit("online",users);
socket.on("new",function(username)
{
console.log(username+"is connected");
socket.username=username;
usernames[username]=username;
console.log(usernames);
io.emit("users",
{total: users,
names:usernames});
}

);

socket.on('disconnect' ,function(){
users--;
console.log(users);

});
});


http.listen(3000, function(){
console.log('listening on *:3000');
});


And here is the client side:

<script>
var socket = io();
$(document).ready(function(){
var name=prompt("What is your name?","");
if (name!="")
{
socket.emit("new",name);
}
socket.on("online",function(users)
{
alert(users);
})
socket.on("users",function(usernames)
{
alert(usernames.names.length);
});
});
</script>


What I want is simply to show all connected usernames when a user log in. I am failing to send that usernames array who contains all the connected usernames(I know that I must delete a user on disconnect but I will do that at the end )

Answer

You need to change the usernames array assignment from,

usernames[username]=username;

To,

usernames.push(username);

which will resolve the issue. I have tested this and working fine.

Hope this helps!