Django使用WebSocket

django channels 是django支持websocket的一个模块。

1安装.

|-------------------------|
| pip3 install channels |

2.在settings中添加配置

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]

ASGI_APPLICATION = "django_channels_demo.routing.application"

3.创建websocket应用和路由

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumers


application = ProtocolTypeRouter({
    'websocket': URLRouter([
        url(r'^chat/$', consumers.ChatConsumer),
    ])
})

4.编写处理websocket逻辑业务

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        self.accept()

    def websocket_receive(self, message):
        print('接收到消息', message)
        self.send(text_data='收到了')

    def websocket_disconnect(self, message):
        print('客户端断开连接了')
        raise StopConsumer()

5.启动:

python 复制代码
daphne -b 0.0.0.0 -p xxxx xxxx.asgi:application
相关推荐
Jagger_6 小时前
AI 洪水淹到脖子了:剩下的是什么?我们该往哪儿跑?
后端
曲幽6 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
Victor3567 小时前
MongoDB(28)什么是地理空间索引?
后端
Victor3567 小时前
MongoDB(29)如何创建索引?
后端
皮皮林5518 小时前
面试官:什么是 fail-fast?什么是 fail-safe?
后端
陈随易9 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
雨中飘荡的记忆10 小时前
Multi-Agent + Skills + Spring AI 构建自主决策智能体
后端·spring
我叫黑大帅11 小时前
Go 语言并发编程的 “工具箱”
后端·面试·go
用户83562907805111 小时前
Python 实现 PowerPoint 形状动画设置
后端·python