服务部分
项目名/routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import 应用名.routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
blog.routing.websocket_urlpatterns
)
)
})
settings.py 新增以下设置
INSTALLED_APPS=[
'corsheaders',
'channels',
'应用'
]
ASGI_APPLICATION = 'ws_server.routing.application'
# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 允许的请求头
CORS_ALLOW_HEADERS = (
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
# 额外允许的请求头
'token',
)
应用/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path('ws/',consumers.ChatConsumer.as_asgi())
]
应用/consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
import asyncio
class ChatConsumer(AsyncWebsocketConsumer):
# 开始
async def connect(self):
await self.accept()
# 销毁
async def disconnect(self, code):
await self.close()
# 接收到信息
async def receive(self, text_data=None, bytes_data=None):
g = 'blog\log.txt'
with open(g) as f:
while True:
await asyncio.sleep(1)
message = f.readline()
print(message)
if message:
try:
await self.send(text_data=json.dumps(message,ensure_ascii=False))
except Exception as e:
...
前端
export default {
data() {
return {
message_list: []
}
},
methods: {
//调用getlog方法执行后续操作
getlog(){
this.initwebsocket()
},
//初始化websocket
initwebsocket() {
//连接服务器
this.websocket = new WebSocket("ws://127.0.0.1:8000/ws/")
//指定事件回调
this.websocket.onmessage = this.websocketOnMessage; //后端返回的时候怎么做
this.websocket.onopen = this.websocketOnOpen; //开启通信怎么做
this.websocket.onerror = this.websocketOnError; //有错误的时候怎么做
this.websocket.onclose = this.websocketOnClose; //关闭通信
},
//后端返回的时候怎么做
websocketOnMessage(msg) {
this.message_list.push(JSON.parse(msg.data))
},
//开启通信怎么做
websocketOnOpen(e) {
//进入之前先清空数据
this.message_list =[]
},
//有错误的时候怎么做
websocketOnError(e) {
console.log(e)
},
//关闭通信
websocketOnClose(e) {
console.log(e)
}
},
components: {}
}