wetler
wetler

Reputation: 383

Django Channels Private Chat server

I am new to Django channels and the ASGI application itself, so I am a bit confused about how to go while building a private chatting app.

There isn't much tutorial for private chats all are for chat rooms and broadcasting I have few thoughts in mind about how I can make a Private chat, but I am not sure which approach to take.

  1. My first thought is to not use the channel layer and handle each connection separately. By that I mean every time a user comes to the chatting app it will open a connection with the name chat__{userid} and if user_A sends a message to user_B it will first check if user_A is authorized to send a message to user_B then call send method on user_B, after a message is sent send back the confirmation to the user_A.

there is a problem with the above implementation what if a user opens a different tab, how should I handle that.

  1. To establish a connection between users using channel_layers, if both are online while they are chatting with one another, but the problem arises when the user is chatting with multiple users do I need to open multiple WebSocket connections for every conversation. this will solve the multiple tabs and session problem as I can add all of them in the same channel layer.

  2. the Third approach is similar to the 1st approach but the difference is this time use channel layer so that all the session of a single user can be in one channel layer and I can broadcast the message to all the session of the same user.

I think that the 3rd approach is good for this situation but as I mentioned above I don't have much experience in ASGI application and I don't know what will work best.

Any suggestion is appreciated.

Upvotes: 2

Views: 1145

Answers (1)

Matthaus Woolard
Matthaus Woolard

Reputation: 2408

I think your option 3 is correct, make your channel layer name include the user id. Then whenever you connect the consumer can subscribe to this.

If you want persistence so that you can read online messages when you come online I suggest looking into using DCRF and setting up a subscription to the Messages DB record filtering by recipient = user. This will then send you a notification when a message is added if your interested in this feature set add a comment and i will update this answer with a full code example.

Upvotes: 0

Related Questions