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
相关推荐
掘金者阿豪2 小时前
高可用读写分离实战(二):我把数据库主库停了,结果整个集群的反应和我想象的不一样
后端
掘金者阿豪2 小时前
《高可用读写分离集群实战》系列(一)
后端
Dilee2 小时前
Spring AI 2.0.0 Prompt 最小 Demo:system、user、template 到底怎么分工
后端
未秃头的程序猿2 小时前
Java 26正式发布!这3个新特性,让代码量直接减半
java·后端·面试
小旭Coding2 小时前
卧靠!Go 传给前端的 int64 竟然变成了这个?
后端
用户298698530142 小时前
Word 文档文本查找与替换的 Java 实现方案
java·后端
kunge20133 小时前
深度剖析Claude Code 的CLAUDE.md加载逻辑
后端·vibecoding