[Pythonmac-SIG] Closing a blocked socket?
Daniel Tartaglia
daniel_t at earthlink.net
Thu Aug 28 23:30:58 EDT 2003
The code below fails. Socket.accept blocks inside the thread and
doesn't let go, even after the socket was closed. From the error
presented, the socket never actually closes.
I realize that the below is a basic Java idiom but how do you do the
same thing in Python? I ask here because when I asked on the newsgroup
I got no response, so I started thinking it was a Mac only thing...
import unittest
import socket
import threading
import time
class SocketAcceptor ( threading.Thread ):
def __init__( self, socket ):
threading.Thread.__init__( self )
self.socket = socket
self.done = 0
def run( self ):
self.socket.bind( ( "", 3424 ) )
self.socket.listen( 5 )
try:
child, ip = self.socket.accept()
except:
pass
self.done = 1
class SocketTester ( unittest.TestCase ):
def testClose( self ):
for each in range( 4 ):
ss = socket.socket()
acceptor_thread = SocketAcceptor( ss )
acceptor_thread.start()
time.sleep( 1 )
ss.close()
time.sleep( 1 )
self.assertEquals( acceptor_thread.done, 1 )
if __name__ == '__main__':
unittest.main()
More information about the Pythonmac-SIG
mailing list