Search code examples
pythonsocketstcpserversocket

Will TCP Socket Server client connection fd cause memory leak?


I don't if i need to close the client socket handle( conn ) such as "conn.close()" ?

If I run multithread to handler the client socket fd ( conn ). Does it cause memory leak if the server runs too long time?

Will the server not close the client socket fd if client no invokes conn.close()?

Following is my tcp-socket server code:

# coding: utf-8

import socket
import os, os.path
import time

sockfile = "./communicate.sock"

if os.path.exists( sockfile ):
  os.remove( sockfile )

print "Opening socket..."

server = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
server.bind(sockfile)
server.listen(5)

print "Listening..."
while True:
  conn, addr = server.accept()
  print 'accepted connection'
  while True: 
    data = conn.recv(1024)

    if not data:
        break
    else:
        print "-" * 20
        print data
        print "DONE" == data
        if "DONE" == data:
            # If I need to invoke conn.close() here?
            break
print "-" * 20
print "Shutting down..."

server.close()
os.remove( sockfile )
print "Done"

Solution

  • According to the document, close is called when the socket is garbage collected. So if you didn't close it for whatever reason, your program would probably be fine. Provided your socket objects do get GCed.

    However, as a standard practice, you must close the socket, or release whatever resource, when your code is done with it.

    For managing socket objects in Python, check out How to use socket in Python as a context manager?