一、概述
在項目中,需要使用websocket,來展示一些實時信息。
這里使用django 3.1.5
二、django項目
安裝模塊
pip3 install django-cors-headers channels
新建項目websocket_demo
修改websocket_demo/asgi.py
import os from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application # Import other Channels classes and consumers here. from channels.routing import ProtocolTypeRouter, URLRouter # from apps.websocket_app.urls import websocket_urlpatterns from websocket_demo.urls import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_demo.settings') # application = get_asgi_application() application = ProtocolTypeRouter({ # Explicitly set 'http' key using Django's ASGI application. "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), })
修改websocket_demo/settings.py
注冊corsheaders和channels,corsheaders主要是用來解決跨域問題的。
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'corsheaders', # 注冊應用cors 'channels' ]
注冊中間件
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', # 注冊組件cors ]
最后一行增加以下內容
# 跨域增加忽略 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'GET', 'OPTIONS', 'PATCH', 'POST', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) # 指定ASGI的路由地址 ASGI_APPLICATION = 'websocket_demo.asgi.application'
注意:ASGI是用來做異步請求的。
websocket_demo.asgi.application 表示,websocket_demo/asgi.py里面的application
修改websocket_demo/urls.py
增加websocket路由
from django.contrib import admin from django.urls import path from api.views import ChatConsumer urlpatterns = [ path('admin/', admin.site.urls), ] websocket_urlpatterns = [ # 前端請求websocket連接 path('wx/', ChatConsumer.as_asgi()), ]
修改api/views.py
from django.shortcuts import render from channels.generic.websocket import WebsocketConsumer import json import time # Create your views here. class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): """ 接收消息 :param text_data: 客戶端發送的消息 :return: """ print(text_data) poetryList = [ "雲想衣裳花想容", "春風拂檻露華濃", "若非群玉山頭見", "會向瑤台月下逢", ] for i in poetryList: time.sleep(0.5) self.send(i)
說明:
這里主要介紹receive,它是用來接收/發送消息的。即可以接收客戶端,也就是vue發送的消息。也可以發送消息給客戶端。
最后啟動django項目即可
三、vue項目
新建一個vue項目,安裝ElementUI 模塊即可。
新建test.vue

<template> <div style="width: 70%;margin-left: 30px;margin-top: 30px;"> <el-table :data="content" style="width: 100%;"> <el-table-column prop="info" label="實時執行日志" > </el-table-column> </el-table> <br> <el-button type="primary" @click="onSubumit">提交</el-button> </div> </template> <script> export default { data() { return { content:[], } }, mounted: function() { }, methods: { onSubumit(){ // 清空消息 this.content = [] // 執行webSocket this.webSocket() }, webSocket() { const _this = this; if (typeof (WebSocket) == 'undefined') { this.$notify({ title: '提示', message: '當前瀏覽器無法接收實時報警信息,請使用谷歌瀏覽器!', type: 'warning', duration: 0 }); } else { // 實例化socket const socketUrl = 'ws://127.0.0.1:8000/wx/'; this.socket = new WebSocket(socketUrl); // 監聽socket打開 this.socket.onopen = function() { console.log('瀏覽器WebSocket已打開'); //發送字符: _this.socket.send(JSON.stringify({ 'username': "xiao", 'msg': "hello", })); }; // 監聽socket消息接收 this.socket.onmessage = function(msg) { // 追加到內容顯示列表中 _this.content.push({"info":msg.data}) }; // 監聽socket錯誤 this.socket.onerror = function() { _this.$notify({ title: '錯誤', message: '服務器錯誤,無法接收實時報警信息', type: 'error', duration: 0 }); }; // 監聽socket關閉 this.socket.onclose = function() { console.log('WebSocket已關閉'); } } }, } } </script> <style> </style>
訪問測試頁面
點擊提交,效果如下:
本文參考鏈接:
https://blog.csdn.net/qq_16687863/article/details/112340769