Search code examples
javascriptpythonsocket.iopython-socketio

Convert socket.io Javascript code to python-socketio


I have a javascript using socket.io.
I would like to convert this javascript file to python:

io.on('connection',(socket)=>{
    
    let nsData = namespaces.map((ns)=>{
        return {
            img: ns.image,
            endpoint: ns.endpoint
        }
    })
    // console.log(nsData)
    socket.emit('nsList',nsData);
})

This is what I have in python:

@sio.event
def connect(socket_id, environ):
    # ???

Solution

  • On the documentation, it is stated that you just need to either use a return statement or use the .emit() function. https://python-socketio.readthedocs.io/en/latest/server.html#emitting-events As the docs say, you simply need to

    sio.emit('nsList', nsData, room=socket_id)
    

    That will emit the nsList event with the content nsData. However, I do not know what nsData is. It seems to simply be a map statement, which can be done with the map() function. As GFG states, you simply need to map out the namespaces. https://www.geeksforgeeks.org/python-map-function/ Assuming namespaces is a list, you can do something similar to this:

    def mapNsData(ns):
        return { 'img': ns.image, 'endpoint': ns.endpoint }
    

    Then, use the map function:

    nsData = list(map(mapNsData, namespaces))
    

    Tada! Now, you have a list to send to the client!