Django-Channels 2 Apache CentOS 7部署

时间:2018-09-11 13:20:12

标签: django apache websocket django-channels daphne

我无法让Apache通过Daphne服务websocket。
requirements.txt
Django==2.0.7 channels==2.1.3 asgiref==2.3.2 redis==2.10.6
settings.py

CHANNEL_LAYERS = {
    "default":{
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost"), 6379],
        },
        "ROUTING": "myapp.routing.channel_routing",
    },
}

ASGI_APPLICATION = "myapp.routing.application"
USE_WEBSOCKETS = True

routing.py

#..imports  

websocket_urlpatterns = [
    url(r"", MyConsumer),
]

application = ProtocolTypeRouter({
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                websocket_urlpatterns
            )
        )
    )
})

asgi.py

#.. imports

os.environment.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
application = get_default_application()

MyConsumer.py

#..imports

class MyConsumer(WebsocketConsumer):
    def websocket_connect(self, event):
        Logger.log("Connected " + json.dumps(event))
        self.send({
            "type": "websocket.accept"
        })

    def websocket_receive(self, event):
        Logger.log("Receive " + json.dumps(event))

    def websocket_disconnect(self, event):
        Logger.log("Disconnected " + json.dumps(event))

httpd.conf

#...
RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC, OR]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://127.0.0.1:9001%{REQUEST_URI} [P, QSA, L]

supervisord.conf

;...    
[fcgi-program:asgi]
socket=tcp://127.0.0.1:9001
command=/var/www/venv/bin/daphne -u /run/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myapp.asgi.application
numprocs=2
process_name=asgi%(process_num)d
directory=/var/www/venv/myapp/
autostart=true
autorestart=true
stdout_logfile=/tmp/asgi.log
redirect_stderr=true

在javascript中,我只是尝试连接:

var location = window.location
var socket = new WebSocket('ws://' + location.host + ':9001' + location.pathname)
socket.onopen = function(e){
    console.log('open', e)
}
socket.onerror = function(e){
    console.log('error', e)
}
socket.onclose = function(e){
    console.log('close', e)
}

每次访问页面时,它都会在一段时间后显示WebSocket connection to 'ws://127.0.0.1:9001/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET并在控制台中显示错误并关闭消息。
我遵循了readthedocs提供的示例设置,并使用了Nginx实例,但是它给出了相同的错误。
似乎后端未接收到该消息,因此我认为设置中必须包含某些内容,即消息传递队列或Redis服务器。我想念什么?

1 个答案:

答案 0 :(得分:0)

是的,我花了很多时间对与您类似的设置进行故障排除。我目前在centos 7.5服务器上一起运行channel2,daphne,redis和apache。终于完美地工作了。

我发现使用AsyncConsumer进行故障排除要容易一些,并提供了更多控制权。 尝试做:

from channels.consumer import SyncConsumer, AsyncConsumer
class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        # when the socket connects
        print(event)
        await self.send({
            "type": "websocket.accept"
        })

然后,您将看到传入的数据。

对于Apache,像您一样,我使用重写引擎。 (在虚拟主机文件中)

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://127.0.0.1:9001%{REQUEST_URI} [P,QSA,L]

希望您能弄清楚! / R