欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Django使用WebSocket

Django使用WebSocket

2025/9/15 12:14:16 来源:https://blog.csdn.net/qq_36797488/article/details/146971944  浏览:    关键词:Django使用WebSocket

django channels 是django支持websocket的一个模块。

1安装.

pip3 install channels

 2.在settings中添加配置

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应用和路由

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumersapplication = ProtocolTypeRouter({'websocket': URLRouter([url(r'^chat/$', consumers.ChatConsumer),])
})

4.编写处理websocket逻辑业务

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumerclass 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.启动:

daphne -b 0.0.0.0 -p xxxx xxxx.asgi:application

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com