一、后端
python、django(channels)
1.1、安装channels
pip install channels
pip install channels_redis
1.2、配置项目settings.py文件中的INSTALLED_APPS值
新增channels、项目主站名称
1.3、配置项目settings.py文件中新增ASGI_APPLICATION
1.4、在APP(子站)中新建routing.py文件
from django.conf.urls import url from myChat.conView import ChatService websocket_urlpatterns = [ url(r"ws/", ChatService()), ]
1.5、在APP(子站)中新建conView.py文件
import json import time from channels.generic.websocket import WebsocketConsumer class ChatService(WebsocketConsumer): # 当Websocket创建连接时 def connect(self): print("已连接") self.accept() # 每隔2秒给前端发送数据 for i in range(10): time.sleep(2) self.send(text_data=json.dumps({ 'code': 200, 'message': "djhafkja" })) # 当Websocket接收到消息时 def receive(self, text_data=None, bytes_data=None): print("已收到消息") # 当Websocket发生断开连接时 def disconnect(self, code): print("已断开")
1.6、在项目(主站)中新建routing.py文件
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import myChat.routing application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter( myChat.routing.websocket_urlpatterns ) ), })
1.7、启动
python .\manage.py runserver
二、前端
vue
initWebSocket() { this.websock = new WebSocket("ws://127.0.0.1:8000/ws/"); this.websock.onmessage = this.WebSocketOnMessage; this.websock.onopen = this.WebSocketOnOpen; this.websock.onerror = this.WebSocketOnError; this.websock.onclose = this.WebSocketOnClose; }, WebSocketOnMessage(e) { this.msg.push(JSON.parse(e.data).message); console.log("WebSocketOnMessage"); console.log(e); console.log(JSON.parse(e.data).message); }, WebSocketOnOpen(e) { console.log("WebSocketOnOpen"); console.log(e); }, WebSocketOnError(e) { console.log("WebSocketOnError"); console.log(e); }, WebSocketOnClose(e) { console.log("WebSocketOnClose"); console.log(e); console.log(e.code); },