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
相关推荐
舒一笑19 小时前
Ubuntu系统安装CodeX出现问题
linux·后端
golang学习记20 小时前
GitLens 十大神技:彻底改变你在 VS Code 中的 Git 工作流
前端·后端·visual studio code
敏编程20 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪20 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
一鹿高歌20 小时前
🔥内存炸了!背刺我的竟然是Redisson!!
后端
lizhongxuan20 小时前
AI 的底层思考
后端
databook20 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
Penge66621 小时前
解密 Kafka 与 RocketMQ 消费模型的核心之战
后端
小码哥_常21 小时前
Spring Boot遇上Maven依赖冲突:打怪升级全攻略
后端
用户73440281934221 小时前
Spring Boot 集成 Redis 并调用 Lua 脚本详解
后端