Socket.io does not fire events from client to server

Why is my server not responding to an event sent by the client? I tried some simple examples from the socket.io web page and they seem to work fine.

My goal is to emit an event whenever the user focuses outside the input field, compares the input value on the server and fires the event back to the client.

on the client side

$('#userEmail').focusout(function() { var value = $('#userEmail').val(); // gets email from the input field console.log(value); // prints to console (it works!) socket.emit('emailFocusOut', { userEmail: value }); // server doesn't respond to this }); 

server side

 io.sockets.on 'emailFocusOut', (data) -> console.log(data) 

Additional Information

  • express 3.0rc4
  • socket.io 0.9.10
  • coffee- script 1.3.3
+4
source share
2 answers

If you need any response from the server, the server must send an emit message to the server. console.log not responding to the network.

 var io = require('socket.io').listen(80); io.sockets.on('connection', function(socket) { socket.on('emailFocusOut', function(data) { data.receivedAt = Date.now(); socket.emit('emailFocusOutResponse', data); // answer back }); }); 

Then on the client you can listen to 'emailFocusOutResponse' and process this message.

+5
source

You must place your custom event inside the io.sockets.on function. The following code will work:

 io.sockets.on('connection', function (socket) { socket.on("emailFocusOut", function(data) { console.log(data) // results in: { userEmail: 'awesome' } }) }); 
+5
source

Source: https://habr.com/ru/post/1437013/


All Articles