javascript - Node.js chat app with username variables not working -
i'm making chat app in node.js based on tutorial socket.io. purpose user enter in username , message. chat display "username: message". username text field disappear after first entry. have working except chat displaying message username. chat displays 4 messages instead of one, both variables 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 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>
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); }); });
Comments
Post a Comment