我编码一个真实的时间聊天使用Django和渠道
我的密码
consumers.py:
class ChatConsumer(WebsocketConsumer):
def connect(self):
room_hash = self.scope["url_route"]["kwargs"]["room_hash"]
#self.room_group_name = self.scope["url"]["kwargs"]["hash"]
self.send(text_data = json.dumps({
'type':'room_hash',
'hash': room_hash
}))
chat_room = Room.objects.get(hash = hash)
print(chat_room)
self.accept({
'type': 'websocket.accept'
})
def disconnect(self):
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
print("Message is "+message)
字符串
路由
from django.urls import path
from . import consumers
ws_urlpatterns = [
path('ws/<str:room_hash>/', consumers.ChatConsumer.as_asgi())
]
型
模板脚本:
{{room.hash|json_script:"json-roomhash"}}
<script type = "text/javascript">
let room_hash = JSON.parse(document.getElementById("json-roomhash").textContent)
let url = `ws://${window.location.host}/ws/${room_hash}/`
const chatSocket = new WebSocket(url)
chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
let hash = data.hash
console.log(hash)
}
const form = document.querySelector("#form")
console.log(form)
form.addEventListener('submit', (e)=>{
e.preventDefault()
let message= e.target.message.value
chatSocket.send(JSON.stringify({
'message':message
}))
form.reset()
})
</script>
型
当我试图通过房间的哈希值连接到WebSocket时,它会抛出这个错误。
raise ValueError(“Socket has not been accepted,so cannot send over it”)ValueError:Socket has not been accepted,so cannot send over it应用程序内部异常:Socket has not been accepted,so cannot send over it
1条答案
按热度按时间fhity93d1#
我只需要添加一个pwc和await,代码看起来像这样:
字符串