I have taken some help from django example with socket.io
I found some issue that if I run this code it will only run my socket(5000) but not my main website(at 8000) so I modified it a little bit and the main working code snippets looked something like this
socketio_app/views.py
from django.shortcuts import render
# Create your views here.
import socketio
sio = socketio.Server(async_mode='eventlet', always_connect=True)
@sio.event
def connect(sid, environ):
print('connected to ', sid)
return True
@sio.event
def disconnect(sid):
print("disconnected", sid)
@sio.on('chat')
def on_message(sid, data):
print('I received a message!', data)
sio.emit("chat", "received your msg"+str(data))
Similarly as in the github repo they overrided runserver command I made some changes to it to make it look like I also called super to run main website coded along with threaded socket io at port 5000
socketio_app/management/commands/runserver.py
from django.core.management.commands.runserver import Command as RunCommand
from socketio_app.views import sio
import os
class Command(RunCommand):
help = 'Run the Socket.IO server'
def handle(self, *args, **options):
if sio.async_mode == 'threading':
super(Command, self).handle(*args, **options)
elif sio.async_mode == 'eventlet':
import eventlet
import eventlet.wsgi
from ProLogger.wsgi import application
import threading
def fun():
print(os.system("sudo kill -9 `sudo lsof -t -i:5000`"))
eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5000)), application)
t = threading.Thread(target=fun)
t.start()
import time
time.sleep(3.5)
super(Command, self).handle(*args, **options)
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ProLogger.settings")
import socketio
from socketio_app.views import sio
application = get_wsgi_application()
application = socketio.WSGIApp(sio, application)
Now the first question is 1. is it a good practice to run in a thread the next question is since I m using gunicorn to run the code so runserver command will never be called and my eventlet code of socket io will not be executed. my gunicorn bash script looks something like this
[program:gunicorn]
command=gunicorn --name ProLogger-gunicorn --workers 2 ProLogger.wsgi:application --bind 0.0.0.0:8000 --timeout 100 -k ev$
directory=/home/ubuntu/ProLoggerBackend/
stdout_logfile=/home/ubuntu/logs/gunicorn_output.log
stderr_logfile=/home/ubuntu/logs/gunicorn_error.log
autostart=true
autorestart=true
startretries=10
Now since runserver is not called so my socket io code won't run, so how should I proceed
EDIT
It worked when I ran the application on the other port (5000). In my nginx configuration I have a line like proxy_pass 127.0.0.1:8000 Is this the reason that it wasn't working on port 8000 but the same code worked on port 5000 with both WSGI and socket on same port 5000 without any error like "address already in use"