[英]Websocket disconnect with Channels in Django
I'm beginner with Django.我是 Django 的初学者。 I would like to use websockets with Channels.我想将 websockets 与 Channels 一起使用。 In this way I'm following this tutorial to create a simple chat.通过这种方式,我正在按照本 教程创建一个简单的聊天。
I show you my files.我给你看我的文件。
chat/consumers.py聊天/消费者.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
}))
My template file room.html:我的模板文件 room.html:
<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</html>
Root routing configuration:根路由配置:
# mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
And my routing.py file:还有我的 routing.py 文件:
# chat/routing.py
from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
]
When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/ , I'm getting the following message error:当我运行我的 ASGI 服务器并到达页面http://127.0.0.1:8000/chat/Test/时,我收到以下消息错误:
HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
[Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
C:\Users\kevin\Envs\myproject\lib\site-packages\autobahn\websocket\protocol.py:2801:processHandshake
C:\Users\kevin\Envs\myproject\lib\site-packages\txaio\tx.py:429:as_future
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\ws_protocol.py:82:onConnect
--- <exception caught here> ---
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\server.py:198:create_application
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\staticfiles.py:41:__call__
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\routing.py:61:__call__
]
WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]
Would you have an idea of the problem?你知道这个问题吗? :) :)
This question is similar, but no answer has been provided.这个问题类似,但没有提供答案。
Thank you !谢谢 !
EDIT编辑
I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it.我注意到一件奇怪的事,如果我在我的文件 routing.py 中输入了错误的代码,服务器不会注意到它。 It is like it doesn't read this file.就像它没有读取这个文件一样。 For example if I turn the routing.py file like this:例如,如果我像这样转动 routing.py 文件:
# chat/routing.py
from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
]
The server doesn't display any error message.服务器不显示任何错误消息。
I had the same error.我有同样的错误。 I assume we're both following the same tutorial.我假设我们都遵循相同的教程。
For me it was the extra dollar sign at the end of the path in chat/routing.py:对我来说,它是 chat/routing.py 中路径末尾的额外美元符号:
# chat/routing.py
from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
path('ws/chat/<str:room_name>/$', consumers.ChatConsumer),
]
When the '$' was removed, everything worked.删除“$”后,一切正常。
I have found my error... I put the file routing.py inside of the first directory: sitetest\ Whereas I had to put it inside of sitetest\sitetest\我发现了我的错误...我将文件 routing.py 放在第一个目录中:sitetest\ 而我不得不将它放在 sitetest\sitetest\ 中
I'm beginner with Django.我是 Django 的初学者。 I would like to use websockets with Channels.我想将 websockets 与 Channels 一起使用。 In this way I'm following this tutorial to create a simple chat.通过这种方式,我按照本 教程创建了一个简单的聊天。
I show you my files.我给你看我的文件。
chat/consumers.py聊天/消费者.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
}))
My template file room.html :我的模板文件 room.html :
<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</html>
Root routing configuration :根路由配置:
# mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
And my routing.py file :还有我的 routing.py 文件:
# chat/routing.py
from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
]
When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/ , I'm getting the following message error :当我运行我的 ASGI 服务器并到达页面http://127.0.0.1:8000/chat/Test/ 时,我收到以下消息错误:
HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
[Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
C:\Users\kevin\Envs\myproject\lib\site-packages\autobahn\websocket\protocol.py:2801:processHandshake
C:\Users\kevin\Envs\myproject\lib\site-packages\txaio\tx.py:429:as_future
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\ws_protocol.py:82:onConnect
--- <exception caught here> ---
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\server.py:198:create_application
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\staticfiles.py:41:__call__
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\routing.py:61:__call__
]
WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]
Would you have an idea of the problem ?你知道这个问题吗? :) :)
This question is similar, but no answer has been provided.这个问题类似,但没有提供答案。
Thank you !谢谢 !
EDIT编辑
I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it.我注意到一个奇怪的事情,如果我在我的文件 routing.py 中输入了错误的代码,服务器不会注意到它。 It is like it doesn't read this file.就好像它没有读取这个文件。 For example if I turn the routing.py file like this :例如,如果我像这样打开routing.py文件:
# chat/routing.py
from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
]
The server doesn't display any error message.服务器不显示任何错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.