Home > OS >  How to make Python socket accept connections in background in a Flask App?
How to make Python socket accept connections in background in a Flask App?

Time:02-27

I am a beginner in Flask. I am working on a small website in Flask, my goal is to set up a socket accepting connections in background. Here is the code :

@app.route('/dashboard/')
@login_required
def dashboard_page():
    s = lancer_socket()
    accepter_msg(s)   #if i comment out this line, the template loads
    return render_template('dashboard.html',info = info,tel_conns=tel_conns)

However, the function 'accepter_msg' makes the template not load. Here is the code:

 def accepter_msg(socket):
    while True:
        Client, addresse = socket.accept()
        print('Connecté à: '   addresse[0]   ':'   str(addresse[1]))
        start_new_thread(threaded_client, (Client, ))

My goal is to load the dashboard page, and to make the socket accept the connections and receive data in background (after that, i will refresh the template with the modified variables (info and tel_conns) :

render_template('dashboard.html',info = info,tel_conns=tel_conns)

I need to use a simple python socket and not a socketio or anything else. Can anyone help me ?

CodePudding user response:

If you are setting up a socket server to accept websocket connections, consider using Flask-SocketIO.

CodePudding user response:

The socket.accept call is a blocking function call, which means the function does not return until a client connects to it. So you render_template will not even start when this blocking function call does not return. The function does not return simply means that it is hanging there.

Client, addresse = socket.accept()

If you really want to use socket.accept, you need it make it a non-blocking socket. How to do that? This realpython article has nice examples.

https://realpython.com/python-sockets/

Also read this official documentation Socket Programming HOWTO to get a good understanding of socket programming.

https://docs.python.org/3/howto/sockets.html

  • Related