Django – Channels used
Django==2.1, Channels-redis ==2.1.3, channels-redis==2.3.0
1. Add basic Settings related to Channels to settings.py:
Add channels to INSTALLED_APPS # ASGI routing address specified ASGI_APPLICATION = "RestaurantOrder. Routing. Application" # websocket configuration backend database relies on # specified channel layer redis [channel Layer is a communication system that allows multiple consumer instances to communicate with each other and with external Djanbo programs.] CHANNEL_LAYERS = {'default': {'BACKEND': 'channels_redis. Core. RedisChannelLayer', 'CONFIG' : {" hosts ": [(' 127.0.0.1, 6379)],},}},Copy the code
2. Compile a routing file named Settings /routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
Copy the code
3. Add the routing.py file to the subapplication directory
from django.urls import path
from chat.consumers import ChatConsumer
websocket_urlpatterns = [
path('ws/chat/', ChatConsumer),
]
Copy the code
4. Write consumer.py for the child application
The import json from channels. Generic. Websocket import AsyncWebsocketConsumer # asynchronous, Class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): # connect method triggers self.room_group_name = 'chat_test' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # disconnect triggers when the connection is closed # Leave room group await self.channel_layer.group_discard(self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): Loads (text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): Message = 'Test chat room: '+ event['message'] # Send message to WebSocket (text_data=json.dumps({'message': message }))Copy the code
At this point, the Django back end has WebSocket connectivity
5. How does front-end VUE connect to back-end Websocket?
5.1 Local localhost The proxy needs to be configured in vue.config.js
'/ws':{// target: ', timeout: 60000, // target: ', // changeOrigin: true, ws: true, pathRewrite: {'^/ws': '/ws' // override,}}Copy the code
5.2 The Nginx Agent needs to be configured in the Online Environment
location /ws { proxy_pass https://abc.com/ws; proxy_connect_timeout 4s; proxy_read_timeout 360s; proxy_send_timeout 12s; Proxy_http_version 1.1; proxy_set_header Upgrade "websocket"; Proxy_set_header Connection "Upgrade"; # important}Copy the code
5.3 the code
InitWebSocket () {// initialize websocket // var wsuri = "ws://127.0.0.1:8080"; var ws_scheme = window.location.protocol === "https:" ? "wss" : "ws"; Var ws_on_line =ws_scheme + '://' + window.location.host + '/ws/chat/' var weburl = GLOBAL.httpWsUrl + "ws/chat"; // var ws_scheme = window.location.protocol==="https:"?" wss":"ws" this.websock = new WebSocket(ws_on_line); this.websock.onopen = this.websocketonopen; this.websock.onmessage = this.websocketonmessage; this.websock.onerror = this.websocketonerror; // this.websock.onclose = this.websocketclose; }, websocketonopen() {// After the connection is established, send the data console.log(" establish the connection "); Var actions = {message: "connection test"}; this.websocketsend(JSON.stringify(actions)); }, websocketonError (e) {// Connection failed to establish console.log(" connection error", e); this.initWebSocket(); }, webSocketonMessage (e) {this.websocket_data = json.parse (e.data); Console. log("websocket-res", json.stringify (this.websocket_data)) console.log(" Receive backend data type",typeof(this.websocket_data)) Var h = this.$createElement; This.hrender = h("p", null, [h("div", [h("div", json.stringify (this.websocket_data.message)), }, //}),], null,]); If (this.websocket_data.message['result']){const instance = this.$notify ({title: "prompt ", message: this.hrender, type: "Success ", // duration: 0, // whether the configuration is automatically closed, if 0 is not closed}); }}, webSocketSend (Data) {// Data is sent this.websocket.send (Data); }, webSocketClose (e){// Close console.log(' disconnect ',e); },Copy the code
At this point, the Websocket connection between The VUE and Django backend is established, and the backend can customize the sending method to send messages to the client during specific code execution phases
From channels. Layers import get_channel_layer channel_layer = get_channel_layer() def send_ws_msg(data): group_name = "chat_test" async_to_sync(channel_layer.group_send) (group_name, { 'type': 'chat_message', 'message': data }) returnCopy the code