[Tutor] Threading and Sockets
Wayne Werner
waynejwerner at gmail.com
Mon Nov 15 16:16:30 CET 2010
Hi,
I'm working on creating a server/client bit of software using threading and
sockets (it's a project so I can't use something like twisted), and I've run
into a slight issue with my server. My server currently looks like this:
class ClientThread(threading.Thread):
def __init__(self, socketdata, server):
threading.Thread.__init__(self)
self.conn = socketdata[0]
self.details = socketdata[1]
self.server = server
def run(self):
''' Method called when the Thread.start() method is called. '''
global CONNCOUNT
CONNCOUNT -= 1
print("Getting data from {0}:{1}: ".format(self.details[0],
self.details[1]), end='')
data = self.conn.recv(1024)
print(data)
if data == 'quit':
self.server.stop()
self.conn.close()
class Server(threading.Thread):
def __init__(self, port=1500, max_connections=5):
''' Setup the server elements. '''
threading.Thread.__init__(self)
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(('localhost', 1500))
self.server.listen(5)
self.keeprunning = True
def run(self):
global CONNCOUNT
while self.keeprunning:#CONNCOUNT > 1:
ClientThread(self.server.accept(), self).start()
self.stop()
def stop(self):
''' Stop the server. '''
print("Stopping server... maybe...")
self.keeprunning = False
# Close the socket connection
self.server.close()
print("Server stopped.")
(CONNCOUNT is currently not used - I was using it to stop my server)
My issue is that when I send 'quit' the server does (sort of) close, but (I
think) the self.server.accept() is blocking, so until I try connecting a few
more times, the server doesn't actually finish.
So that's really my only question - how do I make my server completely stop
when I'm done? Pointing me towards documentation would be perfectly fine,
preferably with a hint about which function(s) I should look at.
TIA
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101115/8ce2ba66/attachment.html>
More information about the Tutor
mailing list