pythonnode.jssocket.iopython-socketio

Why is my python socket client not sending events to my node.js server?


Question

I have a simple express server (just showing the socket, the route is default):

io.on('connection', (socket) => {
  socket.emit('identify')
  
  socket.on('identity', (data) => {
    activeUsers.push(data['name'])
    socket.name = data['name']
    console.log('Connection from ' + socket.name)
  });

  io.on('disconnect', (data) => {
    activeUsers.splice(indexOf(socket.name))
    console.log(socket.name + ' disconnected.')
  })
  
  io.on('message', (data) => {
    console.log(data['message'])
  });
});

I then wrote a python client, and connection worked fine:

@io.event
def connect():
  print('connected')

@io.on("identify")
def identity():
  io.emit("identity", {"name": "isaiah08"})

However, when i changed identify to be:

@io.on("identify")
def identity():
  io.emit("identity", {"name": "isaiah08"})
  io.emit("message", {"message": "I WILL EAT YOU"})

It did not log the message. Why is this?

Note

Yes, I created a socket in the / route:

<script>
  var socket = io();
</script>

And I am connection to the right website.


Solution

  • You aren't registering the event handler for message correctly on your server, so the message is arriving, but your message handler to receive it isn't configured properly.

    Change this:

      io.on('disconnect', (data) => {
        activeUsers.splice(indexOf(socket.name))
        console.log(socket.name + ' disconnected.')
      })
      
      io.on('message', (data) => {
        console.log(data['message'])
      });
    

    to this:

      socket.on('disconnect', (data) => {
        activeUsers.splice(indexOf(socket.name))
        console.log(socket.name + ' disconnected.')
      })
      
      socket.on('message', (data) => {
        console.log(data['message'])
      });
    

    These messages come to the socket, not to the io object. You wrote it correctly with the "identify" message, but not with these other two messages.