chatuur chatuur - 7 months ago 40
Javascript Question

Socket.io socket.emit not passing data to server

I was trying my hands on Socket.io.
I have the following code.

This is my index.html.

<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');

function sayHello(){
var msg = document.getElementById('m');
console.log(msg); <- This is getting printed.
socket.emit('message', msg.value);
msg.value='';
return (false);
}

// $('form').submit(function(){
// socket.emit('chat message', $('#m').val());
// $('#m').val('');
// return false;
// });
// socket.on('chat message', function(msg){
// $('#messages').append($('<li>').text(msg));
// });
</script>
</body>
</html>


This is my server.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("GO!") <- This is getting printed
socket.on('chat message', function(msg){
console.log(msg); <- This is not getting printed.
io.emit('chat message', msg);
});
});

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


I have cloned the sample project from the Socket.io website. I was trying to modify some code by replacing the Jquery with VanillaJS.

Answer

You are listening for chat message but emitting message from client. Event name provided with .emit must match with the event name being listened on the server in .on handler.

//SERVER SIDE CODE
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("GO!") < -This is getting printed
  socket.on('chat message', function(msg) {
    console.log(msg); < -This is not getting printed.
    io.emit('chat message', msg);
  });
});

http.listen(3001, function() {
  console.log('listening on *:3001');
});
<!doctype html>
<html>

<body>
  <ul id="messages"></ul>
  <form action="" onsubmit="return sayHello()">
    <input id="m" autocomplete="off" />
    <button>Send</button>
  </form>
  <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
  <script>
    var socket = io.connect('http://127.0.0.1:3001/');

    function sayHello() {
      var msg = document.getElementById('m');
      console.log(msg); < -This is getting printed.
      socket.emit('chat message', msg.value);
      //-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
      msg.value = '';
      return (false);
    }
  </script>
</body>

</html>