我正在尝试使用以下代码设置django频道
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
from django.conf.urls import url
from consumers import ChatConsumer
#supposed to be on the main routing
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
websocket_urlpatterns = [
url(r'^ws/chat/$', ChatConsumer),
]
#after linking to above as chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
ASGI_APPLICATION = 'chatsys.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
INSTALLED_APPS = [
...
'channels',
]
//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
这就是整个代码的全部内容。该脚本已加载到主页上,并希望连接到ws /chat/
网址,但会在网页加载后立即抛出警报alert("Connection closed.");
,以便连接永远不会完成。
诊断错误的地方也不那么容易,因为频道仍然相对较新且不断变化。
new WebSocket("ws://35.185.80.98/chat/")
WebSocket { url: "ws://35.185.80.98/chat/", readyState: 0, bufferedAmount: 0, onopen: null, onerror: null, onclose: null, extensions: "", protocol: "", onmessage: null, binaryType: "blob" }
Firefox can’t establish a connection to the server at ws://35.185.80.98/chat/.