django默认不支持websocket,需要安装组件:
shellpip install channels daphne
PythonINSTALLED_APPS = [
"daphne",
"channels",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"web.apps.WebConfig"
]
PythonASGI_APPLICATION = "ws_demo.asgi.application"
Pythonimport os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ws_demo.settings')
# application = get_asgi_application()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": URLRouter(routing.websocket_urlpatterns),
})
Pythonfrom django.urls import re_path
from app01 import consumers
websocket_urlpatterns = [
re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
Pythonfrom channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
class ChatConsumer(WebsocketConsumer):
def websocket_connect(self, message):
# 有客户端来向后端发送websocket连接的请求时,自动触发。
# 服务端允许和客户端创建连接。
self.accept()
def websocket_receive(self, message):
# 浏览器基于websocket向后端发送数据,自动触发接收消息。
print(message)
self.send("不要回复不要回复")
# self.close()
def websocket_disconnect(self, message):
# 客户端与服务端断开连接时,自动触发。
print("断开连接")
raise StopConsumer()
本文作者:GYC
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!