shuttong down socket from another thread

A

Ajay

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
 

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

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top