Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django channels - Echo example not working

I'm following the instructions in the documentation site, but I got stuck in the echo example, the websocket is created correctly and it's connected to the server but when I send anything to the server I'm not getting any response (In the example says I should see an alert window with the same message that I send into the socket but I don't, although I've changed the alert for a console.log but still), what I'm doing wrong?

In settings.py:

INSTALLED_APPS = {
    ...
    'channels',
    'myapp',
    ...
} 

...
# Channels settings
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "myapp.routing.channel_routing",
    },
}

In routing.py:

from channels.routing import route
from myapp.consumers import *

channel_routing = [
    route("websocket.receive", ws_receive),
]

In consumers.py:

def ws_receive(message):
    # ASGI WebSocket packet-received and send-packet message types
    # both have a "text" key for their textual data.
    message.reply_channel.send({
        "text": message.content['text'],
    })

In asgi.py

import os
from channels.asgi import get_channel_layer

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")

channel_layer = get_channel_layer()

Then I run: python manage.py runserver, and in my browser I go to the server url and in the console I put the following:

socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
    alert(e.data);
}
socket.onopen = function() {
    socket.send("hello world");
}

Again, at this point I should see an alert window (or the console.log message) but I get nothing.

response

The requests that I made have a status of pending (Although I read here and the first comment says it's normal)

requests

And the server output looks like this:

server-output

Every time that I've tried to send something through the websocket in the browser, the server just print CONNECT but no log from the js console is showing.

Edit: I've tested websockets in my browser against echo.websocket.org and I got the answer as expected:

test-websocket

like image 463
pazitos10 Avatar asked Jul 07 '16 03:07

pazitos10


Video Answer


1 Answers

I changed to an older version of twisted and it fixed it. Hth

like image 137
Nickyt Avatar answered Oct 02 '22 01:10

Nickyt