How to close the tcp connection fully when using asyncio open_connection() when connected to server?

208 Views Asked by At

In the following code, the client opens connection to server using asyncio.open_connection():

self.client_reader, self.client_writer = await asyncio.open_connection(
            self.host, 
            8080, 
            ssl = context)

And the client receives data using,

await asyncio.wait_for(self.client_reader.read(1024), timeout=10)

When the server is abruptly closed (Control + Z), doing lsof -i:8080 on server returns

ubuntu@ubuntu-server-1:~/services/versionmgmt/tests$ lsof -i:8010
COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    33180 ubuntu   21u  IPv4 339134      0t0  TCP *:8010 (LISTEN)
node    33180 ubuntu   22u  IPv4 339140      0t0  TCP ubuntu-server-1.internal.cloudapp.net:8010->117.195.170.225:64727 (ESTABLISHED)

It looks like I could see connection on server when lsof is used.

How to permanently close the connection from the client side. I have tried closing the write stream using

await self.client_writer.drain()
self.client_writer.close()                
await self.client_writer.wait_closed()

But the code blocks forever near await self.client_writer.wait_closed(), but why?

The connection is fully closed, only when the python client exits.

I checked the documentation to close read streams, but the connection didn't close.

0

There are 0 best solutions below