shuttong down socket from another thread

Ajay abra9823 at mail.usyd.edu.au
Sat Sep 18 06:38:53 CEST 2004


hi!

i have a main application which is run through a GUI. the GUI has a
function 'start server' which starts a server in another thread and a stop
function which should stop this server.
the code is

from Tkinter import *
import tkMessageBox
import tkFileDialog
import socket
import threading
from Queue import Queue

class MainApp:
	def __init__(self, master):
		self.frame = Frame(master)
		self.frame.pack()
                self.th = None
                ...

        def startServer(self):
                self.th = threading.Thread(target=self.doStartServer)
		self.th.start()

        def doStartServer(self):
                print "starting threaded"
		UDPserversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		UDPserversocket.bind((socket.gethostname(), LOCAL_SERVER_PORT))
		print "binded to address: ", socket.gethostname()
		while 1:
			data, address = UDPserversocket.recvfrom(1024)
                        print data

root = Tk()
app = MainApp(root)
root.title("X Privacy Agent")
root.protocol("WM_DELETE_WINDOW", lambda: sys.exit(0))
root.mainloop()

i tried to do the following in stopServer
         def stopServer(self):
                print "stopping"
		if self.th is not None and self.th.isAlive():
			#may not be a clean shut down
			self.th.join(5)
		print "stopped"

first of all, i would like to have a clean termination of the server. so
that if its handling any data etc, it should finish handling it and then
close. secondly the above code doesn't seem to work. after running the
server and then stopping it, when i click on the close window icon, the
application simply crashes.
i could add the variable to the startServer's while loop and then change
the variable in stopServer, but that would work only after the server has
received one datagram (since it will be blocked in the recvfrom call).

any suggestions of how i should go about allowing the user to
1. stop and restart the server
2. and close the application at any time.

thanks

cheers

----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.



More information about the Python-list mailing list