Append a div with an array in Node.js

Naomi

I am creating a chat where there will be a div that displays the users that have connected to the server. The user's name is being taken from a prompt. I have managed to push each connected user to the array but can't figure out how to display that array. At the moment it only appends the div with the name of the individual user but I want them all to be displayed.

<body>

<div id="chatlog" class="col-sm-9">

    <ul id="messages"></ul>
</div>
<div id="online" class="col-sm-3">
    <div id="username"></div>
</div>
<form class="col-sm-12" action="">
    <input id="type" type="text" />
    <input type="submit" id="submit" />
</form>

<script>
    var socket = io();
    var user = prompt("What's your name?");



    $('form').submit(function() {
        socket.emit('chat message', $('#type').val());
        $('#type').val('');
        return false;
    });
    socket.on('chat message', function(msg) {
        $('#messages').append($('<li>').text(msg));
    });
    socket.emit("join", user);
    socket.on("join", function(user) {

        $("#username").append($("<p>").text(user));

    })
</script>



</body>

server.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require("express");
var port = 3000;
var onlineUsers = [];
console.log(onlineUsers);
app.use(express.static(__dirname + '/'));

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

io.on('connection', function(socket) {
console.log('a user connected');
socket.on("join", function(user) {
    socket.emit("join", user);
    onlineUsers.push(user);
    console.log(onlineUsers);

});
socket.on('chat message', function(msg) {
    console.log('message: ' + msg);
    io.emit('chat message', msg);
});
socket.on('disconnect', function() {
    console.log('user disconnected');
});

});

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

I am also open to suggestions how to do this another way but node.js is very new to me and think this might be the easiest way.

rckrd

Send the array of users back to the clients when a user joins. This way all clients will have a updated user list every time a user joins. Below is a suggestion on how you could implement this

server:

socket.on("join", function(user) {
  onlineUsers.push(user);
  io.emit("user list", onlineUsers);
});

client:

socket.emit("join", user);
socket.on('user list', function(onlineUsers) {
  $("#username").empty();
  for(var i=0;i<onlineUsers.length;i++){
    $("#username").append($("<p>").text(onlineUsers[i]));
  }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related