0

I'm setting up Django Channels and so far this is the code I've put up.

#routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import routing as route
from django.conf.urls import url
from consumers import ChatConsumer

websocket_urlpatterns = [
    url(r'^ws/chat/$', ChatConsumer),
]

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})

and in consumers.py

from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        self.send(text_data=json.dumps({
            'message': message
        }))

and settings file

#Channels
ASGI_APPLICATION = 'chatsys.routing.application'

and finally the javascript

//Sockets
var myWebSocket = new WebSocket("ws://" + window.location.host + "/chat/");

myWebSocket.onopen = function(evt) { 
    alert("Connection open ..."); 
};

myWebSocket.onmessage = function(evt) { 
    alert( "Received Message: " + evt.data); 
};

myWebSocket.onclose = function(evt) { 
    alert("Connection closed."); 
};    

// Call onopen directly if socket is already open
if (myWebSocket.readyState == WebSocket.OPEN) myWebSocket.onopen(); 
//End Sockets

What I get when the page loads is the alert for onclose alert("Connection closed."); and also on the console a 404 for the ws connect to ws://35.227.80.72/chat/

Sam B.
  • 2,703
  • 8
  • 40
  • 78

1 Answers1

0

Your code works on my machine, except one thing:

You have set a url routing for /ws/chat/ while you are trying to connect to /chat/

Joseph Bani
  • 644
  • 6
  • 16
  • hmm... this was a while back but you also do note I also changed the same on the javascript and other sections not a copy paste of the django-channels code but yeah now working on data science stuff – Sam B. Aug 28 '18 at 14:43