简体   繁体   中英

Python. Django. Persistent socket.io connection

Is there any way to connect to socket.io server and keep connection alive, like js client do, from django backend?

Code like this:

from socketIO_client import SocketIO
from django.conf import settings

def trigger_socket():
   socket_client = SocketIO(settings.SIO_HOST, settings.SIO_PORT)
   socket_client.emit('cool_task', {})

Works fine, but opens connection at every task emit. Is there any way to avoid it? Or I'm missing something about sockets?

UPD FYI Actually, usage of socket.io to communicate between servers - was stupid idea. Use tornadorpc / xmlrpclib for this kind of task - leave socket.io only on js client side.

Brief:

It's not possible in the way you described. If you want to use django to connect to the something like socket.io, take a look at gevent.io

Detailed:

When deployed with traditional web server, Django is not suitable to handle long time connection tasks due to the process/thread model. To handle long time connection, you need to adopt some event driven web server, such as [gunicorn][2]

It's possible with :

from socketIO_client import SocketIO
from django.conf import settings

def trigger_socket():
    with SocketIO(settings.SIO_HOST, settings.SIO_PORT) as socketIO:
        socketIO.emit('cool_task', {})
        socketIO.wait(seconds=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM