threads and sockets

Discussion in 'Python' started by Ajay, Oct 13, 2004.

  1. Ajay

    Ajay Guest

    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
     
    Ajay, Oct 13, 2004
    #1
    1. Advertisements

  2. Short answer: you can't, and join won't help. Use select on sockets, with a
    timeout, or use twisted.
     
    Diez B. Roggisch, Oct 13, 2004
    #2
    1. Advertisements

  3. 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
     
    Josiah Carlson, Oct 13, 2004
    #3
  4. Ajay

    Elbert Lev Guest

    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
     
    Elbert Lev, Oct 14, 2004
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.