Node.js & Socket.io Adding Username

I am new to socket.io. I would like to know how to add a username to this simple chat using socket.io. Thanks in advance guys. I would like to learn socket programming.

Below is the code for 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> 
+4
source share
1 answer

Take 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 the people object - see the source code (link in the article).

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

Good luck.

+4
source

Source: https://habr.com/ru/post/1500850/


All Articles