How to close a blocked socket?

D

Daniel T.

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?

import unittest
import socket
import threading
import time

class SocketAcceptor ( threading.Thread ):
def __init__( self, socket ):
threading.Thread.__init__( self )
self.socket = socket

def run( self ):
self.socket.bind( ( "", 3423 ) )
self.socket.listen( 5 )
child, ip = self.socket.accept()

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()

if __name__ == '__main__':
unittest.main()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top