django channels

i am having an error while running server for django channels in terminal
''Not Found: /home_page/ ‘’
Broken pipe from (‘127.0.0.1’, 63295)
What can be reason for this?

Many things. You’ll need to provide a lot more details here.

plz let me know codes you need for identifying an issue

Let’s start with some background.

Is this a brand-new project or an extension of an existing project?

What do all your Channels-related configuration items look like? (asgi.py, consumers.py, routing.py, settings.py)

What does the JavaScript code you’re using in the browser look like?

What does the page that contains that JavaScript code look like?

What packages do you have installed in your virtual environment for this?

asgi.py

import os
from channels.routing import ProtocolTypeRouter, URLRouter

from Jobglobel.Jobglobel_Modified.Jobglobel import routing
from django.core.asgi import get_asgi_application
from channels.security.websocket import AllowedHostsOriginValidator

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Jobglobel.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AllowedHostsOriginValidator(
        URLRouter([
            routing.websocket_urlpatterns
        ])
    )
})

consumers.py

from channels.consumer import AsyncConsumer
from channels.exceptions import StopConsumer
from time import sleep
import asyncio


class home_page_consumer(AsyncConsumer):
    async def websocket_connect(self, event):
        await self.accept()

    async def websocket_receive(self, event):
        for i in range(20):
            await self.send(text_data=str(i))   # To send data to client
            await asyncio.sleep(1)

    async def websocket_disconnect(self, event):
        raise StopConsumer()

routing.py

from django.urls import path
from . import consumers


websocket_urlpatterns = [
    path('ws/home_page/', consumers.home_page_consumer.as_asgi()),
    path('ws/user_login/', consumers.user_login_consumer.as_asgi(),
         name='user_login_channel'),
    path('ws/user_signup/', consumers.user_signup_consumer.as_asgi(),
         name='user_signup_channel'),
]

setting.py

ASGI_APPLICATION = 'Jobglobel_Modified.asgi.application'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

javascript in template

<script>
        var ws = new WebSocket(
            'ws://' +
            window.location.host +
            'ws/home_page/' 
            
        )
        ws.onopen = function () {
            console.log('Websocket Connection open...')
            ws.send("Hi, message from client")
        }
        ws.onmessage = function (event) {
            console.log("Message received from server...", event)
            console.log(event.data)
            document.getElementById("ct").innerText = event.data
        }
    </script>

Packages That i have installed in virtualenv

asgiref==3.6.0
async-timeout==4.0.2
autopep8==2.0.2
beautifulsoup4==4.11.2
channels==4.0.0
channels-redis==4.0.0
Django==4.1.7
django-livereload==1.7
django-unused-media==0.2.2
djangorestframework==3.14.0
msgpack==1.0.5
Pillow==9.4.0
pycodestyle==2.10.0
pytz==2022.7.1
redis==4.5.1
six==1.16.0
soupsieve==2.4
sqlparse==0.4.3
tzdata==2022.7

Side note: I strongly encourage you to use the WebsocketConsumer (or AsyncWebsocketConsumer) instead of the raw consumers. (No, it’s not required, but it does make things a lot easier to work with.)

The issue with what I see here is:

You don’t have a / between the windows.location.host and ws/home_page/.

i tried by putting / before ws/home_page/ Still it is showing me same error

Next questions then are what is your INSTALLED_APPS setting, and do you have redis installed and running on you system?

What is the complete output that you are seeing from the runserver command when you run this and try to open a connection?

installed apps

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Jobglobel',
    'rest_framework',
    'channels',
    'livereload',
    'django_unused_media',
]
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

I need the complete output - starting with the run command for runserver.

1 Like

Something’s not installed correctly because you’re not running the Daphne version of runserver.

Review the installation docs at Installation — Channels 4.0.0 documentation and ensure you’ve got everything installed and configured correctly.

but sir it is optional thing, i have installed redis_channel layer

I’m not only talking about redis here. Recheck your installation of everything related to channels.

i tired by reinstalling redis_channel layer as well as entire channels but still it is showing me same error, still let me try to do everything again and let me know you if helps.

And when you’re doing so, make sure you’re following the instructions in the docs completely. Do not skip any steps or take shortcuts.

every settings are correct, but when i keep url empty, it is not showing anything, it might be not accepting websocket connection, i really dont know what to do, by this if you have any idea plz let me know.

websocket_urlpatterns = [
    path('', consumers.home_page_consumer.as_asgi()),
    path('ws/user_login/', consumers.user_login_consumer.as_asgi(),
         name='user_login_channel'),
    path('ws/user_signup/', consumers.user_signup_consumer.as_asgi(),
         name='user_signup_channel'),
]

js in template

<script>
        var ws = new WebSocket('ws://'+ window.location.host)
        ws.onopen = function () {
            console.log('Websocket Connection open...')
            ws.send("Hi, message from client")
        }
        ws.onmessage = function (event) {
            console.log("Message received from server...", event)
            console.log(event.data)
            document.getElementById("ct").innerText = event.data
        }
    </script>

Please show your current INSTALLED_APPS setting, the list of packages installed in your virtualenvironment, details of how you installed redis, proof that you have redis running, and the full output of your runserver command from the start with one attempt at trying to connect.

Note: Regarding my reference to redis above, I am not asking about the Python package. I’m asking about the redis server that is necessary for this.

i have installed channel layer by following ‘pip install channels_redis’
if you are asking about redis channel layer then here is settings for that which i am using

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}
asgiref==3.6.0
async-timeout==4.0.2
autopep8==2.0.2
beautifulsoup4==4.11.2
channels==4.0.0
channels-redis==4.0.0
Django==4.1.7
django-livereload==1.7
django-unused-media==0.2.2
djangorestframework==3.14.0
msgpack==1.0.5
Pillow==9.4.0
pycodestyle==2.10.0
pytz==2022.7.1
redis==4.5.1
six==1.16.0
soupsieve==2.4
sqlparse==0.4.3
tzdata==2022.7

I am not talking about the Python part of this, I am talking about the redis server.

This python module is a redis client. There’s a separate component, a server, that the client software communicates with. That is what I’m asking about here.

Review the docs at Tutorial Part 1: Basic Setup — Channels 4.0.0 documentation