WebSocket-соединение с 'ws://127.0.0.1:8000/ws/work/' не удалось:
Я не могу получить доступ к WebSocket, пока следую этому проекту: https://www.youtube.com/watch?v=SF1k_Twr9cg&t=2498s&ab_channel=CodeWithStein. С 47:23
consumers.py import json
from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
routing.py
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]
asgi.py import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter
import room.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings')
application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) })
room.html
{% block scripts %}
{{ room.slug|json_script:"json-roomname" }}
<script>
const roomName = JSON.parse(document.getElementById("json-roomname").textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
chatSocket.onmessage = function (e) {
console.log("onmessage");
}
chatSocket.onclose = function (e) {
console.log("onclose");
}
</script>
{% endblock %}