On some platforms os.close
does not work for socket file descriptors. This is most noticeable with Windows.
1def create_socket_noncompliant(samplehost, sampleport, samplebuffersize):
2 import socket
3 socket.socket.settimeout(10.0)
4 socket = socket.socket()
5 socket.connect((samplehost, sampleport))
6 print(socket.recv(samplebuffersize))
7 # Noncompliant: socket.shutdown is not called before closing the socket.
8 socket.close()
1def create_socket_compliant(samplehost, sampleport, samplebuffersize):
2 import socket
3 socket.socket.settimeout(10.0)
4 socket = socket.socket()
5 socket.connect((samplehost, sampleport))
6 try:
7 print(socket.recv(samplebuffersize))
8 finally:
9 # Compliant: socket.shutdown is called before closing the socket.
10 socket.shutdown(socket.SHUT_WR)
11 socket.close()