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
相关推荐
AC赳赳老秦7 分钟前
云原生AI故障排查新趋势:利用DeepSeek实现高效定位部署报错与性能瓶颈
ide·人工智能·python·云原生·prometheus·ai-native·deepseek
Mr. zhihao14 分钟前
深度解析 OpenAI Assistant API:从核心架构到实战场景
python·架构
~远在太平洋~16 分钟前
debian系统已安装python3.12却无法执行python命令
chrome·python·debian
2501_9419820521 分钟前
告别手动,Java 自动化调用企微外部群的深度实践
开发语言·python
一个有梦有戏的人24 分钟前
Java 网络编程核心:BIO、NIO、AIO IO 模型深度解析与实战
java·网络·后端·netty·nio
Nightmare00428 分钟前
切换conda环境的时候输出zstandard could not be imported. Running without .conda support.
开发语言·python·conda
weixin_3954489129 分钟前
build_fsd_luyan_from_rm——注释
开发语言·windows·python
程序员南飞33 分钟前
算法笔试-求一个字符串的所有子串
java·开发语言·数据结构·python·算法·排序算法
烂尾主教34 分钟前
提示词工程:核心原理与实战指南
人工智能·python·chatgpt·回归·aigc
开发者小天37 分钟前
python中使用jupyter notebook 绘制正态分布直方图 密度图 小提琴图 模仿企鹅喙长分布图
开发语言·python·jupyter