Socket.io - socket.emit() SOCKET.IO

Socket.io - socket.emit()  

Socket.io - socket.emit()

socket.emit

The main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and binary data is supported too.

Let’s make it so that when the user types in a message, the server gets it as a chat message event. The script section in index.html should now look as follows:

<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(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
  });
</script>

And in index.js we print out the chat message event:

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

The result should be like the following video:

Download free E-book of SOCKET.IO


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries