Ajay <ab******@mail.usyd.edu.au> wrote in message news:<ma**************************************@pyt hon.org>...
hi!
how can i stop a server socket running in a thread other than the main
thread? if the server socket was a local variable of the function started
by the child thread, would calling join work?
Here is how you do what this:
import socket, threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
HOST = ''
PORT = 50007
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#! blocking operatioms on this socket (accept) will timeout
self.s.settimeout(1)
self.s.bind((HOST, PORT))
self.s.listen(5)
self._stop = False
def stop(self):
self._stop = True
def run(self):
while 1:
try:
if self._stop:
print "stop requested"
break
conn, addr = self.s.accept()
print "connection from", addr
except socket.timeout:
print "timeout"
except socket.error:
print "socket.error"
break
self.s.close()
def TimerFucn(t):
print "TimerFucn"
t.stop()
# you can do t.close(). accept() will throw an exception
# in thos case all the stuff with stop() is not needed
listener = MyThread()
t = threading.Timer(10, TimerFucn, (listener,))
t.start()
listener.start()
while 1:
s = raw_input()
if s[0] == 'q':
break