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>
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.
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