无法使用Django通道测试websockets

luaexgnf  于 2023-10-20  发布在  Go
关注(0)|答案(1)|浏览(87)

我试图测试我的websockets,但我得到'404未找到错误'
我不知道为什么我得到错误..我检查了我的代码很多次,但仍然没有用。请看一下。
这是我的settings.py

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp'
]

ASGI_APPLICATION = 'routing_pro.asgi.application'

这是我的网站consumers.py

from channels.consumer import SyncConsumer,AsyncConsumer

class MySyncConsumer(SyncConsumer):
    def websocket_connect(self,event):
        print('Websocket connected...',event)
        
    def websocket_receive(self,event):
        print('Websocket Recived...',event)
    def websocket_disconnect(self,event):
        print('Websocket disconnected...',event)



class MyASyncConsumer(AsyncConsumer):
    def websocket_connect(self,event):
        print('Websocket connected',event)
        
    def websocket_receive(self,event):
        print('Websocket Recived',event)
    def websocket_disconnect(self,event):
        print('Websocket disconnected',event)

这是我的asgi.py文件:

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
import myapp.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'routing_pro.settings')

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(
myapp.routing.websocket_urlpatterns.
        myapp.routing.websocket_urlpatterns
    )
})

这是我的网站routing.py

from django.urls import path

from . import consumers

websocket_urlpatterns = [
    path('ws/sc/',consumers.MySyncConsumer.as_asgi()),
    path('ws/ac/',consumers.MyASyncConsumer.as_asgi()),

]

这是我得到的错误:

Could not connect to ws://127.0.0.1:8000/ws/sc/
15:12:33
Error: Unexpected server response: 404
Handshake Details
Request URL: http://127.0.0.1:8000/ws/sc/
Request Method: GET
Status Code: 404 Not Found
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: xO8WLEzNls1BeFdnyPJlbw==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000
Response Headers
Date: Sat, 30 Sep 2023 09:42:33 GMT
Server: WSGIServer/0.2 CPython/3.10.11
Content-Type: text/html; charset=utf-8
X-Frame-Options: DENY
Content-Length: 2100
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
wbgh16ku

wbgh16ku1#

您需要在websocket_connect中使用self.accept()

相关问题