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
相关推荐
why1514 分钟前
6.4 计算机网络面试题
后端·计算机网络
404.Not Found8 分钟前
Day43 Python打卡训练营
开发语言·python
油头少年_w13 分钟前
Python爬虫之数据提取
python
heart000_114 分钟前
Go语言基础知识总结(超详细整理)
开发语言·后端·golang
残*影18 分钟前
Spring 中注入 Bean 有几种方式?
java·后端·spring
江湖十年23 分钟前
在 Go 语言中如何实现协程池
后端·面试·go
程序员的世界你不懂28 分钟前
Appium+python自动化(九)- 定位元素工具
python·appium·自动化
Humbunklung38 分钟前
Rust 数据类型
开发语言·后端·rust
南玖yy39 分钟前
深入理解 x86 汇编中的重复前缀:REP、REPZ/REPE、REPNZ/REPNE(进阶详解版)
开发语言·网络·汇编·后端·算法·bochs
寻月隐君39 分钟前
Rust 所有权:从内存管理到生产力释放
后端·rust·github