i'm having a problem in socket.io client, because i can't show the list of all the users username in my client. I'm just new in socket.io and i know how to code in the server side. I'm having difficulty in the client side programming. All i just want to do is to show the connected users username in my client.html <div id="users"></div>
.
Here is some of my code in server.js
var users = [];
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('adduser', function (user) {
socket.user = user;
users[user] = user;
console.log(users);
});
socket.on('disconnect', function () {
console.log('User: ' + users[socket.user] + ' has disconnected');
delete users[socket.user];
console.log(users)
});
socket.on('update', function () {
users[user] = user;
console.log('Current users: ', users);
});
});
});
Here is my simple client.html to insert the username to the array users[]
<html>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
</script>
<div style="float:left;width:150px;border-right:2px solid black;height:510px;padding:10px;overflow:scroll-y;text-align:center;">
<b>Users</b>
<div id="users"></div>
</div>
</html>
Thanks in advance. :)
Your best bet is to emit back to the clients the user list when player connects or disconnects. Here is some example code:
var users = [];
app.get('/', function (req, res) {
res.sendfile(__dirname + '/test.html');
});
io.sockets.on('connection', function (socket) {
socket.on('adduser', function (user) {
socket.user = user;
users.push(user);
updateClients();
});
socket.on('disconnect', function () {
for(var i=0; i<users.length; i++) {
if(users[i] == socket.user) {
delete users[users[i]];
}
}
updateClients();
});
function updateClients() {
io.sockets.emit('update', users);
}
});
And in your Client code:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('connect', function (){
socket.emit('adduser', prompt("What's your name?"));
});
var userList = [];
socket.on('update', function (users){
userList = users;
$('#user').empty();
for(var i=0; i<userList.length; i++) {
$('#user').append("<h1>" + userList[i] + "</h1>");
}
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>Users</b>
<div id="users">
<p id="user"></p>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With