[英]Django Channels can't "socket.send" when trying to constantly send data to client from server
我正在嘗試使用頻道在 django 上創建游戲。 為此,我需要服務器在一定時間后向客戶端發送數據。 我設法實現了它,但現在我無法通過 socket.send 將任何內容發送回服務器。 我很難弄清楚為什么會這樣。
我試圖實現的是讓服務器不斷發送數據並從客戶端接收數據以將其保存到數據庫。 第二部分是我目前被困的地方。
編輯:忘了說,我在沒有while
循環的情況下運行了代碼,然后 socket.send 按預期工作。
consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
from channels.db import database_sync_to_async
from django.utils.crypto import get_random_string
from .models import Model
import asyncio
import json
import random
from hashlib import pbkdf2_hmac
@database_sync_to_async
def get_round():
a = Model.objects.last()
return a.round_number
class Game(AsyncWebsocketConsumer):
async def connect(self):
self.connected = True
self.room_name = 'gameName'
self.room_group_name = 'game_room'
await self.channel_layer.group_add(
self.room_group_name,
self.room_name
)
await self.accept()
while self.connected:
await asyncio.sleep(5)
server_seed = get_random_string(length=64)
public_seed = random.randint(0, 999999)
round = await get_round()
hash = pbkdf2_hmac('sha256', bytes(server_seed, 'utf-8'), bytes(public_seed), round)
result = int(hash[0:8].hex(), 16) % 15
await self.send(text_data = json.dumps({
'round_result': result
}))
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
self.connected = False
async def receive(self, text_data):
data = json.loads(text_data)
print(data)
# nothing is happening here
# await self.send(text_data = json.dumps({
# 'data': data
# }))
home.html
<script>
let socket = new WebSocket('ws://localhost:8000/ws/game/game_name/')
socket.onopen = function (e) {
console.log('Socket connected')
}
socket.onmessage = function (e) {
console.log(e)
const data = JSON.parse(e.data)
if(data.round_result) {
document.querySelector('#result').innerHTML = data.round_result
}
}
socket.onclose = function (e) {
console.log('Socket closed')
}
document.querySelector('#bet-submit').onclick = function(e) {
const id = 12312313123123123
const value = document.getElementById('value').value
socket.send(JSON.stringify({
'id': id,
'value': value
}))
}
</script>
我有同樣的問題,我解決了添加
await asyncio.sleep(time)
后
await self.send()
在我的例子中,我使用發送 function 發送視頻幀,所以我設置time = 0.00000001
以在兩次發送之間具有低延遲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.