I'm going to proceed with WebSocket in django. However, url not found occurs, but I can't find the cause.
- CMS/CMS/settings.py
... INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CMS', 'main', ] ASGI_APPLICATION = 'CMS.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } }
- CMS/CMS/routing.py
from django.core.asgi import get_asgi_application from django.urls import path,re_path from . import consumers websocket_urlpatterns = [ path('ws/alarm_endpoint/', consumers.JpConsumer.as_asgi()), ]
- CMS/CMS/consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.layers import get_channel_layer class JpConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): await self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({ 'message': message }))
- main/static/common/notification.js
var socket = new WebSocket("ws://" + window.location.host + "/ws/alarm_endpoint/"); socket.onopen = function () { console.log('WebSocket connection opened.'); // 연결이 열리면 서버로 데이터를 보낼 수 있습니다. socket.send(JSON.stringify({ 'message': 'Hello, Server!' })); }; socket.onmessage = function (e) { var data = JSON.parse(e.data); console.log('Received message from server:', data.message); // 서버로부터 받은 데이터를 처리할 수 있습니다. alert('Received message from server: ' + data.message); }; socket.onclose = function (event) { if (event.wasClean) { console.log('Connection closed cleanly, code=' + event.code + ', reason=' + event.reason); } else { console.error('Connection died'); } }; socket.onerror = function (error) { console.error('WebSocket Error: ' + error); }; // 페이지를 닫거나 이동할 때 WebSocket 연결을 닫습니다. window.onbeforeunload = function () { socket.close(); };
html
... {% "static 'common/notification.js' %}"> ...
When you call notification.js in html, WebSocket connection to 'ws://127.0.1:8000/ws/alarm_endpoint/'failed: error occurs in the browser developer tool.
I have no idea.
And, when I'm running, I'm running in development mode Running with "python manage.py runserver".