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 分钟前
Python高级特性详解:从基础到进阶
python·github
祭曦念7 分钟前
学Rust3次都放弃?这篇文章帮你避开90%的新手劝退
后端
iPadiPhone20 分钟前
万亿级流量的基石:Kafka 核心原理、大厂面试题解析与实战
分布式·后端·面试·kafka
wzhidev20 分钟前
04、Python核心数据类型详解:从一段诡异的调试说起
开发语言·python
wzhidev22 分钟前
05、Python流程控制与函数定义:从调试现场到工程实践
linux·网络·python
Thomas.Sir23 分钟前
第十一章:深入剖析 Prompt 提示工程
python·prompt
Fortune7923 分钟前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
2401_8785302129 分钟前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
2401_8735449232 分钟前
使用Black自动格式化你的Python代码
jvm·数据库·python