jkang14
jkang14

Reputation: 63

Django Channels: How to keep socket alive

I am trying to use django channels and templates to implement authentication. I know that there is an authentication section in the official website, but I have a question about the socket, which is created in the client side via templates.

From my understanding, django templates multi-page application, so if I create a socket in login.html, the socket will be disconnected in main.html, and I have seen it happen.

Is there a way to keep the socket alive even if I navigate to different pages?

Upvotes: 0

Views: 1496

Answers (1)

Sreekanth Reddy Balne
Sreekanth Reddy Balne

Reputation: 3424

You can't keep a socket alive between pages. socket's connection is persistent until it is closed from either the client-side or server-side.

When you move from one page login.html to another main.html, the connection is closed and you need to reinstate it.

the working model of a socket:

Socket is a persistent connection where you are able to communicate in real-time.

Room consists of a set of Sockets.

When a Socket subscribes to a Room, it can listen to all the communication that is happening in that Room. i.e, when someone sends data in that room, it is received by all sockets listening to it.

So, you keep this Room details unique, eg: for user1 you can have room1. When user1 tries to connect to server with a socket1, you authenticate him and subscribe/register his socket1 to room1.

Similarly, when you change page to main.html, you create socket2 and subscribe it to room1 again based on user auth.

Upvotes: 1

Related Questions