Hi,
I am new to Django and am trying to set up secure WebSocket communication between a Django-based backend and a React-based frontend. To address my issue, I reviewed the following thread, which was closed some time ago:
Secure websocket (with http)
Previously, I was working with HTTP, and my app was functioning perfectly. However, as soon as I switched to HTTPS, the WebSocket functionality stopped working as expected. I am using “sslserver” with a self-signed certificate. Below are my WebSocket URL patterns:
from django.urls import re_path
from .import consumers
websocket_urlpatterns = [
re_path(r'ws/flag/$', consumers.FlagConsumer.as_asgi()), # WebSocket route
re_path(r'ws/ar/$', consumers.ARConsumer.as_asgi()),
re_path(r'ws/flag-spin/$', consumers.SpinFlagConsumer.as_asgi()),
]
installed apps:
INSTALLED_APPS = [
'packaging.apps.PackagingConfig',
'cargo_storageOpt.apps.CargoStorageoptConfig',
'rest_framework',
'corsheaders',
'channels',
'daphne',
'sslserver',
"django_extensions",
'core.apps.CoreConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
When the application starts, the WebSocket communication is not established, and the terminal shows “Not Found” for all WebSocket URL patterns. Please see the attached picture for reference.
frontend:
const flagSocket = initWebSocket(`wss://${document.location.hostname}:8000/ws/flag/` , setFlag);```
``` useEffect(() => {
const initWebSocket = (url, updateState) => {
let socket = new WebSocket(url);
const reconnect = () => {
console.log(`${document.location.hostname}${window.location.protocol}xxxxxxxxxxxxxReconnecting to WebSocket at ${url}...`);
setTimeout(() => {
initWebSocket(url, updateState); // Reinitialize the socket after a delay
}, 3000); // Retry after 3 seconds
};
socket.onopen = () => {
console.log("WebSocket connection opened:", url);
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Data received:", data);
if (data.is_computing !== undefined) {
updateState(data.is_computing);
setButtonClicked(false);
}
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
socket.close(); // Close socket on error to trigger reconnect
};
socket.onclose = (event) => {
// console.log("WebSocket closed:", event);
if (!event.wasClean) {
reconnect(); // Only reconnect if the close was unexpected
}
};
return socket;
};