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
相关推荐
chushiyunen9 分钟前
python中的魔术方法(双下划线)
前端·javascript·python
深蓝轨迹17 分钟前
@Autowired与@Resource:Spring依赖注入注解核心差异剖析
java·python·spring·注解
人工智能AI技术22 分钟前
Python 3.14.3更新!内存优化与安全补丁实战应用
python
2401_8916558125 分钟前
此电脑网络位置异常的AD域排错指南的技术文章大纲
开发语言·python·算法
不要秃头的小孩36 分钟前
50. 随机数排序
数据结构·python·算法
qq_4176950544 分钟前
实战:用OpenCV和Python进行人脸识别
jvm·数据库·python
1941s1 小时前
Google Agent Development Kit (ADK) 指南 第五章:工具集成与自定义
人工智能·python·langchain·agent·adk
故事和你911 小时前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
chushiyunen1 小时前
pycharm注意力残差示例
ide·python·pycharm
luom01022 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端