Websocket connection disconnects after few minutes

Hello
I have a problem with PubSub Websocket connection in Python the connection just disconnects.
After 7 minutes of the connection i get:

websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason

Found the same problem on this forum https://discuss.dev.twitch.com/t/solved-getting-disconnected-from-pubsub-after-7-minutes/7458

So i tried to disable the websockets internal ping system and use manual PINGS:

connection = websockets.connect(url, ping_interval=None)

async def keepAlive():
    async with connection as socket:
        while(True):

            ping = json.dumps({
                "type": "PING" })

            await socket.send(ping)
            res = await socket.recv()
            print(res)
            await asyncio.sleep(100 + random.randrange(1,50))

loop.create_task(keepAlive())

Any tips how to keep the connection alive?

You either

  • Didn’t add any valid topics (with valid auths) to listen to
  • Are not ping/ponging correctly.

When you PING do you get a PONG?

Hey there! Thanks for the reply!

I see that i didn’t specify more details, my bad.
I do have a successful connection to PubSub’s “channel-points-channel-v1”

with the response:

{‘type’: ‘RESPONSE’, ‘error’: ’ ', ‘nonce’: ‘123456789p’}

To answer your question about PING:
Yes i do get a PONG as a response.

Here is the basic code:

url = “wss://pubsub-edge.twitch.tv”

loop = asyncio.get_event_loop()

connection = websockets.connect(url, ping_interval=None)

async def keepAlive():
async with connection as socket:
while(True):

        ping = json.dumps({
            "type": "PING" })

        await socket.send(ping)
        res = await socket.recv()
        print(res)
        await asyncio.sleep(100 + random.randrange(1,50))

async def listen():
async with connection as socket:
data = json.dumps({
“type”:“LISTEN”,
“nonce”: “123456789p”,
“data”: {
“topics”: [“channel-points-channel-v1.” + channel_id],
“auth_token”: access_token,
}
})
await socket.send(data)

    resp = await socket.recv()

    dec_resp = json.loads(resp)

    print(dec_resp)
    
    # while(loop.is_running):
        
    async for msg in socket:
        pass

       # Some logic...

loop.create_task(keepAlive())

loop.run_until_complete(listen())

Sorry for my late response.

Looks like you are doing everything you are supposed to be doing.

So could be your ISP/server provider is doing something weird and killing the connection or you have something in your code blocking/killing the connection.

My python is super rusty so I can’t debug/test your code easily

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.