0

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"
scott1028
  • 417
  • 2
  • 7
  • 16

2 Answers2

2

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?

Community
  • 1
  • 1
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
  • If my language is not python, such as C++ due to there is no GC. Do I have to close the cliend socket fd? – scott1028 Jul 15 '16 at 06:21
1

One way to find out is to test it and see! Here is a little Python script that I ran on my Mac (OS X 10.11.5). If I un-comment the holdSockets.append() line, this script errors out ("socket.error: Too many open files") after creating 253 sockets. However, if I leave the holdSockets.append() line commented out, so that the sockets can be garbage collected, the script runs indefinitely without any errors.

#!/bin/python

import socket
import time

count = 0

holdSockets = []

while True:
   count += 1
   nextSock = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
   #holdSockets.append(nextSock)
   time.sleep(0.1)
   print "Created %i sockets" % count
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234