Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect socket EOF in Python asyncio

I'm writing a simple socket server that receives some messages.

The only challenge left: If the client sends EOF, the connection does not close or the EOF is detected.

#!/usr/bin/env python

import asyncio


class Protocol(asyncio.Protocol):
    def connection_made(self, transport):
        self.peername = transport.get_extra_info("peername")
        print("Connection from %s" % (self.peername,))
        self.transport = transport

    def eof_received(self):
        print("end of stream!")
        self.close()

    def close(self):
        self.transport.close()

    def connection_lost(self, exc):
        print("Connection lost with %s" % (self.peername,))

    def data_received(self, data):
        print("received: %s" % data)


def main():
    loop = asyncio.get_event_loop()
    coro = loop.create_server(Protocol, "localhost", 1337)
    server = loop.run_until_complete(coro)

    print("Listening on %s..." % (server.sockets[0].getsockname(),))

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print("exiting...")

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()

if __name__ == "__main__":
    main()

I'm connecting there with strace nc localhost 1337. When I send lines to nc, they are receieved of course. When I type Ctrl-D in nc, strace instantly reveals that socket was closed.

But the python script does not notice the EOF and keeps the connection open. When I kill nc, then the connection closes.

What can I do to close the connection in the asyncio protocol as soon as nc sends the EOF?

like image 541
TheJJ Avatar asked Apr 11 '26 09:04

TheJJ


1 Answers

When I type Ctrl-D in nc, strace instantly reveals that socket was closed.

On my system w/ gnu-netcat, I have to run netcat with the -c option for the socket to be shutdown on Ctrl-D. Your script works as expected.

nc6 -x does the same thing, close the socket on eof, not just stdin.

like image 87
Jashandeep Sohi Avatar answered Apr 12 '26 23:04

Jashandeep Sohi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!