Lxs29 Lxs29 - 6 months ago 19
Node.js Question

Node.js chat app with username variables not working

I'm making a chat app in node.js based on a tutorial from socket.io. The purpose is for a user to enter in a username and a message. The chat will display "username: message". The username text field will then disappear after the first entry. I have it all working except for the chat displaying the message with the username. The chat displays four messages instead of one, they say that both variables are undefined.

JS

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});

io.on('connection', function(socket){
socket.on('chat message', function(msg, usn){
io.emit('chat message', msg);
io.emit('chat message', usn);
});
});

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


HTML (Without the style tags)

<!doctype html>


<html>


<head>

<title>Lucas Chat</title>



</head>



<body>

<ul id="messages"></ul>
<form action="">
<input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
</form>



<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
socket.emit('chat message', $('#u').val());
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('chat message', function(msg, usn){
$('#messages').append($('<li>').text(usn + ": " + msg));
});
</script>



</body>
</html>

Answer

clientside

var socket = io();
  $('form').submit(function(){
    socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
    $('#u').css("display", "none")
    $('#m').css("width", "90%")
    $('#m').val('');
    return false;
  });
  socket.on('receive message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });

and serverside

io.on('connection', function(socket){
  socket.on('send message', function(data){
    io.emit('receive message',data.msg + ':' + data.user);
  });
});