Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js & Socket.io Adding Username

I'm new to socket.io I would like to know how do i add username in this simple chat using socket.io. Thanks in advance guys. I would like to learn socket programming.

The code below is my server.js

//chat service
io.sockets.on('connection', function (socket) {
    socket.on('sendMessage', function (data) {
    socket.broadcast.emit('message', data);
    socket.emit('message', { text: data.text });   
    });   
});

This is my chat client index.html

<!-- index.html -->
<html> 
  <body>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        var socket = io.connect('http://localhost');
        socket.on('message', function (data) {

          $('#chat').append( '<b>' + data.text + '</b>' + '<br />');

        });
            $('#send').click(function () {
            socket.emit('sendMessage', { text: $('#text').val() });
            $('#text').val('');
        });

            $('#text').keypress(function(event) {
              if(event.keyCode == 13) {
                $('#send').click();
                $('#text').val('');
              }
            });

      });
    </script>

    <div id="chat" style="width: 500px; height: 300px; border: 1px solid black">

    </div>    

    <input type="text" name="text" id="text">
    <input type="button" name="send" id="send" value="send">
  </body>
</html>
like image 453
Joenel de Asis Avatar asked Sep 06 '13 04:09

Joenel de Asis


1 Answers

Have a look here - http://www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

The easiest way is to add a people's object - see the source code (link in the article).

If you want to implement rooms as well, read this: http://www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

Have fun.

like image 130
Tamas Avatar answered Sep 19 '22 00:09

Tamas