django websoket教程,前端vue3 cli实时通讯
WebSocket 是一种网络通信协议,它提供了全双工通信通道,允许服务器和客户端之间进行实时、双向的数据传输。这种通信方式相比于传统的 HTTP 请求/响应模式,能够更有效地处理实时数据,因为它不需要频繁地建立和关闭连接。
WebSocket 在以下场景中非常有用:
- 实时消息和聊天应用
- 实时数据推送,如股票价格更新、新闻更新等
- 多人在线游戏
在 Django 中,我们可以使用 Channels 库来实现 WebSocket 功能。Channels 是一个 Django 项目,它扩展了 Django 以支持异步操作,这使得 Django 可以处理 WebSocket、聊天协议、物联网协议等,而不仅仅是 HTTP。
接下来,我们将介绍如何在 Django 中使用 Channels 设置 WebSocket。
步骤1:安装 Channels
首先,我们需要安装 Channels 包。您可以使用 pip 来完成这个操作:
pip install channels
pip install daphne
步骤2:在 Django 设置中配置 Channels
接下来,我们需要在 Django 设置文件的 INSTALLED_APPS 中添加 ‘channels’。同时,我们需要配置 ASGI_APPLICATION 和 CHANNEL_LAYERS:
# settings.py
INSTALLED_APPS = [
# ...
'channels',
]
ASGI_APPLICATION = 'django2.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer', # 或者选择其他通道层后端
},
}
步骤3:配置 ASGI 应用
现在,我们需要在项目目录的 asgi.py 文件中设置 ASGI 应用:
# asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
from apps import consumers # 导入您的应用的消费者模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django2.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter([
# 添加您的应用的WebSocket路由
path('ws/your_route/', consumers.YourConsumer.as_asgi()),
])
),
})
步骤4:创建 WebSocket 消费者
需要创建一个 WebSocket 消费者。这是在 consumers.py 文件中完成的,新建consumers.py文件:
# consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class YourConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
await self.channel_layer.group_add("group_name", self.channel_name)
print(f"Connected: {self.channel_name}")
async def disconnect(self, close_code):
await self.channel_layer.group_discard("group_name", self.channel_name)
print(f"Disconnected: {self.channel_name}")
async def receive(self, text_data):
pass
async def receive_json(self, content):
pass
async def send_message(self, event):
message = event['message']
response = {
'message': message
}
await self.send(text_data=json.dumps(response))
步骤5:调用方法
# views
from rest_framework.views import APIView
from rest_framework.response import Response
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
class MyApiView(APIView):
def get(self, request, *args, **kwargs):
channel_layer = get_channel_layer()
# 向 group 发送消息
async_to_sync(channel_layer.group_send)("group_name", {
'type': 'send_message',
'message': '6666666'
})
return Response('test')
步骤6:配置路由
# urls
from django.urls import path
from . import consumers
from apps.views import MyApiView
urlpatterns = [
path('test', MyApiView.as_view()),
]
websocket_urlpatterns = [
path('ws/your_route/', consumers.YourConsumer.as_asgi()),
]
urlpatterns += websocket_urlpatterns
到这里我们后端就配置完了。我们去配置vue3,如果一进项目就需要连接websoket的话,需要使用到vueX.
配置vue3 cli
vue:步骤1
在store的index.js文件夹下
# index.js
import { createStore } from 'vuex'
import {showmsg} from "@/utils/msg";
export default createStore({
state: {
socket: null,
},
mutations: {
SET_SOCKET(state, socket) {
state.socket = socket;
},
},
actions: {
disconnectWebSocket({ state, commit }) {
if (state.socket) {
state.socket.close();
commit('SET_SOCKET', null);
}
},
connectWebSocket({ commit }) {
console.log('Attempting to connect WebSocket...')
const socket = new WebSocket('ws://127.0.0.1:8000/ws/your_route/');
socket.onopen = () => console.log('WebSocket连接已建立');
socket.onmessage = (event) => showmsg(JSON.parse(event.data).message);
socket.onclose = () => {
commit('SET_SOCKET', null); // Move this line to the beginning of the onclose handler
console.log('WebSocket连接已关闭');
};
commit('SET_SOCKET', socket);
},
},
})
vue:步骤2
在main.js文件夹下配置
# main.js
import store from '@/store/index'
createApp(App).use(store)
把vueX挂载上就可以了。
自此教程就结束了!
运行django
daphne django2.asgi:application
再运行vue,此时我们在控制台能看见已经连接上了
后端也能看见连接用户的ID,是自动分配的
然后我们再调用一下接口测试一下发送消息成功没有。
这个就是我们后端像前端发送的消息
此时可以看到已经成功了。
教程到这里就结束了。各位赶快试试吧!