Jerielle Jerielle - 5 months ago 17
Node.js Question

Cant retrieve simple broadcast message in the HTML file using NodeJS/Socket.io

I am studying NodeJS together with Socket.io
I have a very simple chat page. But I don't know where's my error.

Here's my simple code:

index.js

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/'));
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
//res.send('<h1>Hello World</h1>');
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
//console.log('a user is connected!');
socket.on('disconnect', function() {
//console.log('user disconnected!');
});
socket.on('chat message', function(msg) {
io.emit('chat message: ' + msg);
});
});

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


index.html

<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="on" /><button>Send</button>
</form>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg) {
console.log(msg); //NO VALUE?
});
</script>
</body>


I can't get the value on this line:

socket.on('chat message', function(msg) {
console.log(msg); //NO VALUE?
});

Answer

The message can not be received on the client because, with

// Server: Receive and send message
socket.on('chat message', function(msg) {
    io.emit('chat message: ' + msg);
}

you emit an event named chat message: ${msg}, but this is an event you are not listening on the client side. When emitting an event you do this by defining the event name first, and then specifying the data as second parameter in JSON format. Changing the code above to

// Server: Receive and send message 
socket.on('chat message', function(data) {
    io.emit('chat message', { message : data.message });
}

will emit the event to the client with the message as the data. Same syntax applies, when sending the event from the client to the sever. So change

// Client: Send message
$('form').submit(function() {
    socket.emit('chat message', $('#m').val());

to

// Client: send message
$('form').submit(function() {
    socket.emit('chat message', {message : $('#m').val()});

When the server answers your event, you can then receive and access the message as follows:

// Client: Receive message
socket.on('chat message', function(data) {
   console.log(data.message); // VALUE :-)
});
Comments