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
相关推荐
葡萄城技术团队1 分钟前
GcExcel V9.2 新特性揭秘:工作簿里的一层自定义 XML
后端
宸津-代码粉碎机16 分钟前
微服务线上踩坑复盘:接口超时、负载倾斜隐形问题根治方案(生产级配置)
java·大数据·人工智能·python·spring
速易达网络24 分钟前
Python + Tkinter 实现基于 TCP/IP 的局域网聊天工具
python·信息与通信
多多鼠25 分钟前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
DyLatte27 分钟前
AI 给了我 8 个优化方案,全都是对的,但没有一个有用
前端·后端·程序员
昔我往昔31 分钟前
pytest日志问题排查记录
python·pytest
Python自动化直播40 分钟前
用 Python 爬虫给 AI 直播间做数据反馈机制
人工智能·python·ai·直播
传奇开心果编程1 小时前
【Go入门练中学】第2课:条件与循环
后端·学习·golang
wno7041 小时前
Spring Security基础使用
java·后端·spring
Go_error1 小时前
那个让我们损失了 47,000 美元 AWS 账单的互斥锁错误
后端