Search code examples
pythondjangopython-3.xwebsocketdjango-channels

Django channels socket not connecting to consumer


I'm new to socket programming & I'm kindof stuck with an issue here. My client is not connecting to consumer.

JavaScript Code

<script>
    // websocket scripts
    var socket = new WebSocket("ws://127.0.0.1:8000/test/")
</script>

Routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            [
                url(r'^ws/test', consumers.TestConsumer),
            ]
        )
    ),
})

The error

WebSocket connection to 'ws://127.0.0.1:8000/test/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

Solution

  • You should try ws://127.0.0.1:8000/ws/test-view/ instead of ws://127.0.0.1:8000/test-view/

    application = ProtocolTypeRouter({
        # (http->django views is added by default)
        'websocket': AuthMiddlewareStack(
            URLRouter(
                [
                    url(r'^ws/test-view', consumers.TestConsumer),
                ]
            )
        ),
    })
    

    Here 'webosocket' defines that you are using ws:// protocol but url(r'^ws/test-view', consumers.TestConsumer) defines that you want to add /ws/test-view/ after localhost to connect to it.