Close socket blocked from consumer

I have an open socket in an infinite loop listening on an XMPP server to receive information regarding the presence of users. Whenever new information is received, it is sent to a consumer to update the list of online users in real time. This is the code for my socket:

# get consumer channel layer
channel_layer = get_channel_layer()

# define socket
s: socket.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock: ssl.SSLSocket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1_2)

# connect to XMPP Server
sock.connect((hostname, port))

# send request
sock.sendall("<presence/>".encode())
while True:
   # receive presence
   presence = sock.recv(4096)
   
   async_to_sync(channel_layer.group_send)("presence_channel", {"type": "presence", "text": presence})

sock.close()

And this is the code of my consumer:

class PresenceConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.name = "presence_channel"

        # join channel
        await self.channel_layer.group_add(self.name, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):
        # leave channel
        await self.channel_layer.group_discard(self.name, self.channel_name)

    # receive message from channel
    async def presence(self, event):
        # Send message to WebSocket
        await self.send_json(event)

I would like to know how I can stop the socket when I disconnect from the consumer (for example because the user refreshes the page or closes the application). I have tried used control flags or global variables, but the socket gets stuck on recv(). I also would not want to set a timeout because I would like to keep receiving information as long as the user remains connected.

Back to Top