LearnToday
LearnToday

Reputation: 2902

Websocket acting different on different client languages

I have this Django Python Channels setup:

class MarketplaceConsumer(GenericAsyncAPIConsumer): queryset = TestChannel.objects.all() serializer_class = TestChannelSerializer permission_classes = [permissions.AllowAny]

    @model_observer(TestChannel)
    async def comment_activity(self, message: TestChannelSerializer, observer=None, **kwargs):
        await self.send_json(message.data)

    @comment_activity.serializer
    def comment_activity(self, instance: TestChannel, action, **kwargs) -> TestChannelSerializer:
        '''This will return the comment serializer'''
        return TestChannelSerializer(instance)

    @action()
    async def subscribe_to_comment_activity(self, user_pk, **kwargs):
        print(user_pk) # PRINTS USER_PK PASSED THROUGH ACTION
        await self.comment_activity.subscribe()

When this is run through JavaScript, I do get the expected result, the action prints the user_pk. enter image description here However, connecting to the same WebSocket using flutter, the user_pk is not printed, meaning the action specified is not even being called. enter image description here Am I implementing this incorrectly with the flutter client?

 final channel = IOWebSocketChannel.connect(
      Uri.parse('ws://127.0.0.1:8000/ws/marketplace/'));
  @override
  void initState() {
    final data = json.encode({
      'action': "subscribe_to_comment_activity",
      'request_id': Helpers.generateId(),
      'user_pk': 'PCs4o8c17xg',
    });
    channel.stream.listen((message) {
      channel.sink.add(data);
      //channel.sink.close(status.goingAway);
      print(jsonDecode(message));
    });
    super.initState();
  }

Upvotes: 2

Views: 111

Answers (1)

LearnToday
LearnToday

Reputation: 2902

Figured this out! The flutter part somehow needs acknowledgement from the backend server. At least that's what I understand.

Adding an accept method to the backend works this out.

 async def accept(self, **kwargs):
        await super().accept(** kwargs)
        print('connected')
        await self.comment_activity.subscribe()

Upvotes: 1

Related Questions