MithunS MithunS - 9 months ago 34
Node.js Question

Socket.io event not firing

Here is the full code :-
index.html

<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { 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; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chatIN', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chatOUT', function(msg){
$('#messages').append('<li><span>'+msg+'</span></li>');
});
});
</script>
</body>
</html>


And here is my index.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.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 socket.io beginner's tutorial, I followed this tutorial
https://socket.io/get-started/chat/

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 socket.io and nodejs.
Thanks

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){...}