redis WebSocket无法与 Postman (django通道)一起使用

5ktev3wc  于 2022-12-11  发布在  Redis
关注(0)|答案(1)|浏览(189)

I have a Django project which I run locally on my mac. And I use channels to create websocket connection.
And an interesting thing happened: The web socket works when I try to connect through .html file:
myTemplate.html

const ws = new WebSocket(
                'ws://'
                + window.location.host
                +'/ws/test/?token='
                +'**mytoken**'
            );'

I can send, and receive messages. But the same URL doesn't work in postman or https://websocketking.com/
Firstly, I thought it is because I run server locally. But on real server nothing works at all.
I searched all stackoverflow and implement everything - to no avail.
asgi.py

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev')
django.setup()

from channels.routing import ProtocolTypeRouter,get_default_application
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import path, re_path
from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack



from myapp import consumers, routing

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

settings

ASGI_APPLICATION = 'spacetime.asgi.application'
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ***
]

vccode console

Django version 4.1.2, using settings 'spacetime.settings.dev'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

vccode console when connecting from html file

HTTP GET /my/socket/view/ 200 [0.01, 127.0.0.1:60258]
WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60260]
WebSocket CONNECT /ws/test/ [127.0.0.1:60260]

xccode console when connectin from https://websocketking.com/

WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60759]
WebSocket REJECT /ws/test/ [127.0.0.1:60759]
WebSocket DISCONNECT /ws/test/ [127.0.0.1:60759]

postman

Request URL: http://127.0.0.1:8000/ws/test/?token=**mytoken**
Request Method: GET
Status Code: 403 Access denied
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 0VRmdvoFhma7lndljwIY6w==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000
Response Headers

token is alright

https://websocketking.com/

Could not connect to "ws://127.0.0.1:8000/ws/test/?token=**mytoken**". You may be able to find more information using Inspector/Dev Tools on this page.

Connecting to ws://127.0.0.1:8000/ws/test/?token=**mytoken**

redis-server

% redis-server            
54336:C 07 Dec 2022 14:42:25.831 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
54336:C 07 Dec 2022 14:42:25.831 # Redis version=7.0.5, bits=64, commit=00000000, modified=0, pid=54336, just started
54336:C 07 Dec 2022 14:42:25.831 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
54336:M 07 Dec 2022 14:42:25.831 * Increased maximum number of open files to 10032 (it was originally set to 256).
54336:M 07 Dec 2022 14:42:25.831 * monotonic clock: POSIX clock_gettime
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 7.0.5 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                  
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 54336
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           https://redis.io       
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

54336:M 07 Dec 2022 14:42:25.832 # WARNING: The TCP backlog setting of 511 cannot be enforced because kern.ipc.somaxconn is set to the lower value of 128.
54336:M 07 Dec 2022 14:42:25.832 # Server initialized
54336:M 07 Dec 2022 14:42:25.832 * Loading RDB produced by version 7.0.5
54336:M 07 Dec 2022 14:42:25.832 * RDB age 14862 seconds
54336:M 07 Dec 2022 14:42:25.832 * RDB memory usage when created 1.05 Mb
54336:M 07 Dec 2022 14:42:25.832 * Done loading RDB, keys loaded: 0, keys expired: 0.
54336:M 07 Dec 2022 14:42:25.832 * DB loaded from disk: 0.000 seconds
54336:M 07 Dec 2022 14:42:25.832 * Ready to accept connections

any ideas why it doesn't work with postman?

8mmmxcuj

8mmmxcuj1#

我不知道它是否会有所不同,但请尝试使您的channel_layers配置为

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

相关问题