0

I am relatively new to JavaScript and subsequently Node + Express.IO. I am trying to build a page that will track in real time connections made by different 'users' to the server. Consequently, when I do include all the functions from the io module, my prompt() and alert do not work anymore. I am running nodemon app.js from my terminal and no compilation errors are showing up when I do so. The alert and prompt work again when I remove all the io functions.

These are the contents of my index.ejs <body> tag:

<body>
<h1>Chatroom</h1>
<script>
    alert("Hello!");
    var name = prompt("What is your name?");
    io.connect();
    io.emit.('got_a_new_user', {name: name});  
    io.on('new_user', function(data) {
    //render this new info in the HTML
         var users = data.users;
         console.log(users);
             if (users != undefined) {
                console.log("\n\n\n" + users);
             // if users is defined, append the new division containing the username
         }
    });
    io.on('disconnect_user', function(data) {
    var users = data.users;
             if (users != undefined) {
                 // If users is defined remove the corresponding HTML element
             }       
    });
</script>
<div id="container">
</div>
</body>

Any help would be much appreciated.

frodo
  • 1
  • 2
  • Hi, could you show how you are including the io module? It should be something like this: `` where src corresponds to your server's folder structure. Also you cannot do `io.on(...)`, instead you need to do the following: `var socket = io.connect` and then `socket.on(...)` – UKatz May 12 '14 at 07:48
  • It seems that my problem was quite trivial, there was an extra period following the emit() function. 'io.emit.('got_a_new_user', {name: name});' should have been 'io.emit('got_a_new_user', {name: name});'. Thanks to all who replied. – frodo May 12 '14 at 16:57

1 Answers1

0

Adding example for the comment added by UKatz,

You will have to connect socket.io from the client as follows,

index.ejs

<script src="http://ip:port/socket.io/socket.io.js"></script>

<script type="text/javascript">
     var socket = io.connect('http://ip:port');
     socket.emit('got_a_new_user', {name: name});  
</script>

Check socket.io documentation for how to connect socket.io with client.

Srikanth Jeeva
  • 3,005
  • 4
  • 38
  • 58