Django频道:连接到套接字

时间:2018-05-31 12:03:14

标签: python django sockets websocket django-channels

我正在设置Django频道,到目前为止这是我提出的代码。

#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
        )
    ),
})

和consumer.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
        }))

和设置文件

#Channels
ASGI_APPLICATION = 'chatsys.routing.application'

最后是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

页面加载时我得到的是onclose alert("Connection closed.");的警报,也是控制台上的一个404,ws连接到ws://35.227.80.72/chat/

1 个答案:

答案 0 :(得分:0)

您的代码可以在我的机器上工作,除了以下几点:

在尝试连接到/ws/chat/时,您已经为/chat/设置了网址路由