演示地址
http://yongma16.xyz/#/onlinewebsocket
asgi配置环境变量
需要添加
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblogsite.settings')
from django.core.asgi import get_asgi_application
# import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblogsite.settings')
django_asgi_app = get_asgi_application()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter,URLRouter#channels的路由
import webchat.routing
# django.setup()
application=ProtocolTypeRouter(
{
"http":get_asgi_application(),
#添加http协议
"websocket": AuthMiddlewareStack(
URLRouter(
webchat.routing.websocket_urlpatterns
#聊天app
)
),
#路由配置
}
)
daphne运行asgi
指定所有ip可以访问,开放8001端口
daphne -b 0.0.0.0 -p 8001 myproject.asgi:application
install supervisor
安装supervisor
yum install -y supervisor
生成配置文件
echo_supervisord_conf > /etc/supervisord.conf
编辑配置文件
[include]
files = supervisord.d/*.ini
表示配置文件读取supervisord.d目录下所有后缀为.ini的文件。
创建配置目录,并创建配置文件
mkdir /etc/supervisord.d/
vi /etc/supervisord.d/asgi.ini
编辑
[fcgi-program:asgi]
# TCP socket used by Nginx backend upstream
socket=tcp://localhost:8001
# Directory where your site's project files are located django项目路径
directory=/data/wwwroot/myblog_project/myblogsite
# Each process needs to have a separate socket file, so we use process_num
# Make sure to update "mysite.asgi" to match your project name 虚拟环境 相对路径下的asgi
command=/data/pyweb/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myblogsite.asgi:application
# Number of processes to startup, roughly the number of CPUs you have
numprocs=4
# Give each process a unique name so they can be told apart
process_name=asgi%(process_num)d
# Automatically start and recover processes
autostart=true
autorestart=true
# Choose where you want your log to go
stdout_logfile=/data/asgilog/asgi.log
redirect_stderr=true
创建文件夹生成daphe的sock文件
$ sudo mkdir /run/daphne/
赋予权限
$ chmod +x /run/daphe
运行
$ supervisord -c /etc/supervisord.conf
ok! 没问题
查看日志
nginx转发websokcet
map
map $http_upgrade $connection_upgrade{
default upgrade;
'' close;
}
处理websocket的请求,发送的请求是:ws://yongma16.xyz/ws/webchat/DjangoVue/
代理配置
location /ws/{
proxy_pass http://127.0.0.1:8001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
发送请求成功!
部署成功!
redismanager查看连接成功!