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
相关推荐
谢亮_vipxieliang3 小时前
Go Worker Pool 设计——从原理到生产级实现
开发语言·后端·golang
青少儿编程课堂3 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
code2cat4 小时前
【随笔】MCP工具注解的信任边界:四个提示如何参与调用决策
python·ai agent·mcp
慢云智慧空间4 小时前
从设备智能到空间理解,慢云科技如何重新定义智慧建筑
python·科技
浮链序4 小时前
用 Claude Haiku 5.5 做子智能体路由,把 Agent 成本砍掉六成
人工智能·python·llm
IT_陈寒4 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
冯一川4 小时前
安装Pyside 6
python
lightning_bug4 小时前
Windows系统Docker+SpringBoot+H5+Mysql+Redis打包部署流程
后端·架构
SingleShadow4 小时前
一文搞懂 CAN 总线:从入门到 STM32 应用
后端
码事漫谈4 小时前
国庆七天,AI圈没一天消停
后端