luisdemarchi
luisdemarchi

Reputation: 1572

Leave only one active connection per user

Using websocket with Django 1.10.5 with Channels 1.0.2. I'm opening a connection with a user token, and I would like the opening to disconnect everyone who is using that user's ID. However the command, even running before accepting the connection, ends up closed the user himself.

Here's how I did it:

def get_group(user):
    if isinstance(user, User):
        uuid = str(user.uuid)
        return Group('user-%s' % uuid)

@channel_session
def websocket_connect(message):
    user = CachedOAuth2Authentication().authenticate(socket_messeger=message)
    if user:
        # Do not use more than one device.
        get_group(user).send({"close": True})

        message.channel_session['user'] = user

        get_group(user).add(message.reply_channel)
        message.reply_channel.send({"accept": True})
    else:
        message.reply_channel.send({"close": True})

Upvotes: 1

Views: 345

Answers (2)

luisdemarchi
luisdemarchi

Reputation: 1572

I found the solution:

For groups, in the "send" method there is the "immediately = False" parameter, just leave it as true and then the function will be executed before adding the new user, so it does not disconnect the new connection.

  def send(self, content, immediately=False):
        """
        Send a message to all channels in the group.

        Sends are delayed until consumer completion. To override this, you
        may pass immediately=True.
        """

Upvotes: 1

tovmeod
tovmeod

Reputation: 888

see this about accepting connections: Websocket using Django Channels

About having only only connection per user, you'll have to either reject new connections based on your logic or send a close message upon a websocket.connect to the relevant reply_channel (or channels), which it seems it is what you are trying to do here.

Upvotes: 1

Related Questions