MithunS MithunS - 1 year ago 46
Node.js Question event not firing

Here is the full code :-

<!doctype html>
<title>Socket.IO chat</title>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
<script src="/"></script>
<script src=""></script>
$(function () {
var socket = io();
socket.emit('chatIN', $('#m').val());
return false;
socket.on('chatOUT', function(msg){

And here is my index.js

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

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

io.sockets.on('connection', function(socket){
socket.on('chatIN', function(msg){
console.log('message:'+ msg);
socket.emit('chatOUT:'+ msg);
socket.on('disconnect', function(){
console.log('user disconnected');

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

I am facing a problem while trying out a beginner's tutorial, I followed this tutorial

Everything seems to be okay till the very last thing, when they build a chat app, and when you hit submit in textbox, it updates the contents of the element.

I can see the messages getting printed in the node js console, but nothing in chrome's console. I also tried debugging it using developer options, but the control just never goes in this method in the index.html.

socket.on('chat message', function(msg){

Can someone please help ? I am really new to and nodejs.

Answer Source

You are sending the wrong message from the server.

On the server, change this:

socket.emit('chatOUT:'+ msg);

to this:

socket.emit('chatOUT', msg);

Your client code is listening for the chatOUT message so that's the exact message name need to send. Here's the matching client code:

socket.on('chatOUT', function(msg){...}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download