threads and sockets

A

Ajay

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?

thanks
 
D

Diez B. Roggisch

Ajay said:
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?

Short answer: you can't, and join won't help. Use select on sockets, with a
timeout, or use twisted.
 
J

Josiah Carlson

Short answer: you can't, and join won't help. Use select on sockets, with a
timeout, or use twisted.

More specifically:

def serverthread(sock):
while not quit:
try:
select(sock, sock, sock, 1)
except:
#handle errors, but don't use a bare except in real code
#close sock if necessary

- Josiah
 
E

Elbert Lev

Ajay said:
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
 

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,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top