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