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
相关推荐
naruto_lnq15 分钟前
Python日志记录(Logging)最佳实践
jvm·数据库·python
yuankoudaodaokou16 分钟前
高帧率扫描如何重塑动态三维扫描与思看科技300fps解决方案
python·科技
rainbow688917 分钟前
Python零基础到精通全攻略
python
毕设源码-朱学姐18 分钟前
【开题答辩全过程】以 基于python网络安全知识在线答题系统为例,包含答辩的问题和答案
开发语言·python·web安全
2301_7657031419 分钟前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
Dxy123931021624 分钟前
Python判断MySQL表是否存在,不存在则创建
python·mysql·adb
BYSJMG39 分钟前
2026计算机毕设推荐:基于大数据的车辆二氧化碳排放量可视化分析系统
大数据·vue.js·python·mysql·django·课程设计
程序员泠零澪回家种桔子42 分钟前
OpenManus开源自主规划智能体解析
人工智能·后端·算法
Pyeako1 小时前
opencv计算机视觉--DNN模块实现风格迁移
python·opencv·计算机视觉·pycharm·dnn·预处理·风格迁移
m0_706653231 小时前
用Python创建一个Discord聊天机器人
jvm·数据库·python