Search code examples
djangoreact-nativewebsocketdjango-channels

React native Websocket connection with Django Channels is open but no messages get through


I have a react native app (android) communicating with Django channels. When connecting to my development server over ws, everything works fine. However, when I try to connect to my remote wss server with the same code, nothing gets through.

The socket connection is showing as OPEN. I even receive this first "connected" message sent from the server to my app:

class RGConsumer(AsyncWebsocketConsumer):
    rooms = []

    async def connect(self):
        self.rooms = []
        await self.join_room('all')
        await self.accept()
        await self.send(text_data=json.dumps({'event': 'connected'}))

    async def join_room(self, room_name):
        if room_name not in self.rooms:
            self.rooms.append(room_name)
            await self.channel_layer.group_add(
                room_name,
                self.channel_name
            )

The problem is that apart from this first message, nothing else goes through. For example whatever I send through this function never gets received by the app:

def send_to_all(event, data=None):
    message = {'type': 'channel_event', 'message': {'event': event, 'data': data}}
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'all',
        message
    )

In the same manner, when I call websocket.send on my app, the receive function of my consumer is not triggered at all.

Once again, this works perfectly fine on my local server, so I assume the code is correct. It's only when connecting the app to the production wss server that it stops working (besides the first connected message that is well received)

Furthermore, even the websocket.onclose function is not getting called if I decide to restart my production server.

Is there any additional settings to allow a proper connection to the wss server that I could be missing?

Let me know if any more code is necessary. I am not sure what else could be needed.


Solution

  • I managed to solve it by creating a different channels route for the mobile WebSocket connection.

    (/ws/ for my website and /mobile-ws/ for the app)

    I still have no clue why using the same endpoint than my website was a problem, or why it worked on development but not production. I'd gladly take a better answer than this.